golang 全切片表达式

今天看别人开源代码的时候,发现别人用切片的语法,有点奇怪,正常我们会写 elements[1:2] , 但是这个人写的是elements[1:2:2], 这样给我直接干懵逼了。我没见过这种。

然后就做了一些功课,分享给大家, 官方有文档。

全切片表达式
主要表达

a [低:高:最大]
构造一个与简单切片表达式具有相同类型、长度和元素的切片a[low : high]。此外,它通过将结果切片设置为 来控制结果切片的容量max - low。只有第一个索引可以省略;它默认为 0。 的核心类型a必须是数组、指向数组的指针或切片(但不是字符串)。切片数组后a

a := [5]int{1, 2, 3, 4, 5}
t := a[1:3:5]
切片t具有类型[]int、长度 2、容量 4 和元素

t[0] == 2
t[1] == 3
对于简单的切片表达式,ifa是指向数组的指针, a[low : high : max]是(*a)[low : high : max]. 如果切片操作数是一个数组,它必须是可寻址的。

如果,则 索引在范围内0 <= low <= high <= max <= cap(a),否则超出范围。常量索引必须是非负的,并且可以 由type 的值 表示int;对于数组,常量索引也必须在范围内。如果多个索引是常数,则存在的常数必须在相对于彼此的范围内。如果索引在运行时超出范围,则会发生运行时恐慌panic。

 

英文源文:https://go.dev/ref/spec

    

Full slice expressions
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. The core type of a must be an array, pointer to array, or slice (but not a string). 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
As for simple slice expressions, if a is a pointer to an array, a[low : high : max] is shorthand for (*a)[low : high : max]. If the sliced operand is an array, it must be addressable.

The indices are in range if 0 <= low <= high <= max <= cap(a), otherwise they are out of range. A constant index must be non-negative and representable by a value of type int; for arrays, constant indices must also be in range. If multiple indices are constant, the constants that are present must be in range relative to each other. If the indices are out of range at run time, a run-time panic occurs.

分类: 默认 标签: 发布于: 2022-03-23 11:51:07, 更新于: 2022-03-23 11:51:26