Published on

Initializing Empty Collection Types in Go

Authors

When coding something you often want to build up a collection over a number of steps. But to do this you first need to initialize the collection type to be empty and add on to it. It was not immediately obvious how to do this in Go. After a quick search it turns out you do this using the make function:

myArray := make([]int, 0, 5)

myMap := make(map[string]string, 5)

In the above:

  • myArray is created with an initial size of 0 and capacity of 5.
  • myMap is created with a capacity of 5, the size for map can be omitted resulting in it having an initial small capcity.