在Go中,如何确定数组中slice的偏移量? [英] In Go, how to determine offset of slice within an array?

查看:62
本文介绍了在Go中,如何确定数组中slice的偏移量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 a1 是数组 a 中的一个切片.可以确定 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)*/)

推荐答案

这里是一种方法:

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

表达式 a [p:e] 返回一个切片,其容量等于 cap(a)-p .给定切片 a1 和后备数组 a ,您可以将p计算为 p = 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)

游乐场示例

这篇关于在Go中,如何确定数组中slice的偏移量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆