x := make([]int, 5)
Makes slice of int
with length 5 and capacity 5 (same as length).
x := make([]int, 5, 10)
Makes slice of int
with length 5 and capacity 10.
x := [5]int{}
Makes array of int
with length 5.
Slices
If you need to append more items than capacity of slice using append
function, go runtime will allocate new underlying array and copy existing one to it. So if you know about estimated length of your slice, better to use explicit capacity declaration. It will consume more memory for underlying array at the beginning, but safe cpu time for many allocations and array copying.
You can explore how len
and cap
changes while append
, using that simple test on <kbd>Go playground</kbd>
Every time when cap
value changed, new array allocated
Arrays
Array size is fixed, so if you need to grow array you have to create new one with new length and copy your old array into it by your own.
There are some great articles about slices and arrays in go:
http://blog.golang.org/go-slices-usage-and-internals
http://blog.golang.org/slices