简体   繁体   English

在Go中,如何确定切片在数组中的偏移量?

[英]In Go, how to determine offset of slice within an array?

I know that a1 is a slice within array a . 我知道, a1是阵列中的一个片段a Is it possible to determine offset of a1 with respect to beginning of a (basically emulating pointer arithmetics)? 是否有可能确定偏移的a1相对于年初的a (基本上模拟指针算术)?

a := [...]int8 {3,1,4,1,5,9,2,6,5,3,5,8,9,7,9,3,2}
a1 := a[3:14]
fmt.Println(a1, "has length", len(a1), "and offset", /*offset(a1,a)*/)

Here's one way to do it: 这是一种实现方法:

a := [...]int8{3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3, 2}
a1 := a[3:14]
fmt.Println(a1, "has length", len(a1), "and offset", cap(a)-cap(a1))

The expression a[p:e] returns a slice with capacity equal to cap(a) - p . 表达式a[p:e]返回一个切片,其容量等于cap(a) - p Given the slice a1 and backing array a , you can compute p as p = cap(a) - cap(a1) 给定切片a1和支持数组a ,您可以将p = cap(a) - cap(a1)计算为p = cap(a) - cap(a1)

playground example 游乐场的例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM