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