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

huangapple go评论88阅读模式
英文:

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

问题

我知道a1是数组a中的一个切片。是否可以确定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, "的长度为", len(a1), "偏移量为", /*offset(a1,a)*/)
英文:

I know that a1 is a slice within array a. Is it possible to determine offset of a1 with respect to beginning of a (basically emulating pointer arithmetics)?

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)*/)

答案1

得分: 4

这是一种方法:

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, "的长度为", len(a1), "偏移量为", cap(a)-cap(a1))

表达式 a[p:e] 返回一个切片,其容量等于 cap(a) - p。给定切片 a1 和支持数组 a,你可以计算 p 为 p = cap(a) - cap(a1)

playground 示例

英文:

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. Given the slice a1 and backing array a, you can compute p as p = cap(a) - cap(a1)

<kbd>playground example</kbd>

huangapple
  • 本文由 发表于 2015年3月18日 05:53:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/29110426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定