英文:
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)。
英文:
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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论