简体   繁体   English

切片在 GO 中是如何工作的?

[英]How slice works in GO?

a = make([]int, 7, 15)

creates implicit array of size 15 and slice( a ) creates a shallow copy of implicit array and points to first 7 elements in array.创建大小为15隐式数组, slice( a ) 创建隐式数组的浅拷贝并指向数组中的前 7 个元素。

Consider,考虑,

var a []int;

creates a zero length slice that does not point to any implicit array.创建一个不指向任何隐式数组的零长度切片。

a = append(a, 9, 86);

creates new implicit array of length 2 and append values 9 and 86 .创建长度为 2 的新隐式数组并附加值986 slice( a ) points to that new implicit array, where slice( a ) 指向那个新的隐式数组,其中

len(a) is 2 and cap(a) >= 2 len(a) is 2并且cap(a) >= 2


My question:我的问题:

is this the correct understanding?这是正确的理解吗?

As I mentioned " Declare slice or make slice? ", the zero value of a slice (nil) acts like a zero-length slice.正如我提到的“声明切片还是制作切片? ”,切片 (nil) 的零值就像一个零长度切片。

So you can append to a []int directly.所以你可以直接附加到a []int

You would need to make a slice ( make([]int, 0) ) only if you wanted to potentially return an empty slice (instead of nil ).只有当您想潜在地返回一个空切片(而不是nil )时,您才需要制作一个切片( make([]int, 0) )。
If not, no need to allocate memory before starting appending.如果没有,则无需在开始追加之前分配内存。
See also " Arrays, slices (and strings): The mechanics of 'append': Nil "另请参阅“数组、切片(和字符串):‘追加’的机制:Nil

a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. nil 切片在功能上等同于零长度切片,即使它指向任何内容。 It has length zero and can be appended to, with allocation.它的长度为零,可以附加到分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM