1
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?

overexchange
  • 15,768
  • 30
  • 152
  • 347
  • You may want to work through the "Tour of Go" (tour.golang.org), especially the slice parts. – Volker Jan 28 '17 at 12:11

1 Answers1

1

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.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250