How slice works in GO?

huangapple go评论81阅读模式
英文:

How slice works in GO?

问题

这是正确的理解吗?

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

创建了一个隐式数组,大小为15,而切片(a)则创建了一个浅拷贝的隐式数组,并指向数组中的前7个元素。

考虑以下代码:

var a []int;

创建了一个长度为零的切片,不指向任何隐式数组。

a = append(a, 9, 86);

创建了一个长度为2的新隐式数组,并追加了值9和86。切片(a)指向这个新的隐式数组,其中

len(a)为2,且cap(a) >= 2

英文:
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.

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. slice(a) points to that new implicit array, where

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


My question:

is this the correct understanding?

答案1

得分: 1

正如我在"声明切片还是创建切片?"中提到的,切片的零值(nil)就像一个长度为零的切片。

因此,你可以直接向a []int追加元素。

只有在你希望可能返回一个空切片(而不是nil)时,才需要创建一个切片(make([]int, 0))。如果不需要,可以在开始追加之前不分配内存。详见"数组、切片(和字符串):'append'的机制:Nil"

一个nil切片在功能上等同于一个长度为零的切片,尽管它指向空。它的长度为零,并且可以通过分配来追加元素。

英文:

As I mentioned "Declare slice or make slice?", the zero value of a slice (nil) acts like a zero-length slice.

So you can append to a []int directly.

You would need to make a slice (make([]int, 0) ) only if you wanted to potentially return an empty slice (instead of nil).
If not, no need to allocate memory before starting appending.
See also "Arrays, slices (and strings): The mechanics of 'append': Nil"

> a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

huangapple
  • 本文由 发表于 2017年1月28日 12:49:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/41906439.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定