Some tips about slices
Published in
1 min readApr 21, 2018
nil slices are slices
Unlink maps, slices can be used without having been allocated:
- a nil slice has a len and a cap of 0,
- you can append to a nil slice, Go will allocate it,
- you can iterate on a nil slice.
As a consequence, no need to initialize slice values of new keys in maps.
can be replaced by
resliced slices share the same underlying array
A slice is a pointer to an array. Reslicing (i.e. doing s2 := s1[a:b]
) creates a new pointer to the same array, with a different starting offset and length.
As a consequence, append will modify both slices…
… unless a new array has been allocated