overexchange
overexchange

Reputation: 1

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.

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?

Upvotes: 1

Views: 174

Answers (1)

VonC
VonC

Reputation: 1323553

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.

Upvotes: 1

Related Questions