Make, Len, and Cap

Most of the time, you create slices using the built-in make function rather than slicing arrays manually.

The make Function

// make([]Type, length, capacity)
mySlice := make([]int, 5, 10)
  • Length (len): The number of elements currently in the slice.
  • Capacity (cap): The total number of elements in the underlying array, starting from the first element in the slice.

Automatic Growth

If you omit the capacity, it defaults to the length. Go will automatically grow the underlying array as you add more elements, but pre-allocating with make is more efficient if you know the approximate size ahead of time.

mySlice := make([]string, 5)
fmt.Println(len(mySlice)) // 5
fmt.Println(cap(mySlice)) // 5

Zero Values

Slices created with make are filled with the zero value of the type (e.g., 0 for ints).