Slice me nice

The length of a slice can, unlike an array change during execution. Its much like an array, but adds some more options.

At first we initialize a slice with make:

manyKnifes := make([]string, 3,5)

Where the first parameter “3” is the length of the slice and “5” is the capacity.


  fmt.Println("How many:", len(manyKnifes))

will give you “How many: 3”.

You may append to an existing slice:

manyKnifes = append(manyKnifes, "katana", "bowie")

Slices are backed by an underlying array, which has the capacity 5 in this example. If with the append this capacity is too small, a bigger array will be allocated. So it is efficient to make the slice big enough. But with append you can grow…

See also


See the full source on github.