关于 go 切片操作符的一个问题?

如下代码:

order := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
pollorder := order[:5:5]
fmt.Println(pollorder)

代码里的 :5:5 是个什么鬼操作?该怎么理解呢?如果是 5:5 ,这个我懂,谢谢哪位大神指点一下!

阅读 2k
1 个回答

这是 go 的 slice 语法,full slice expressions

For an array, pointer to array, or slice a (but not a string), the primary expression

a[low : high : max]

constructs a slice of the same type, and with the same length and elements as the simple slice expression a[low : high]. Additionally, it controls the resulting slice's capacity by setting it to max - low. Only the first index may be omitted; it defaults to 0. After slicing the array a

a := [5]int{1, 2, 3, 4, 5}
t := a[1:3:5]

the slice t has type []int, length 2, capacity 4, and elements

t[0] == 2
t[1] == 3

文档说明很清楚我不翻译了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题