douzhan1238 2017-01-28 04:49
浏览 2

切片在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.

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条回答 默认 最新

  • dotwc62080 2017-01-28 05:52
    关注

    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.

    评论

报告相同问题?