Introduction to Go's Make Function
In my two previous blog posts, I wrote about how to create stacks and queues using the struct data type, which is specifically helpful when one wants to define a maximum capacity for the queue/stack. We can also define a maximum capacity for a slice using the make function, which takes in three arguments: type, length, and capacity (optional, defaults to length if not specified). For type, a slice or a map can be specified. We can initialize a slice in the following way:
import "fmt"
s := make([]int, 2, 3)
for i := range s {
s[i] = i+1
}
fmt.Println(s, len(s), cap(s)) // [1 2] 2 3
Note that if we were to add an element such that we exceed the slice’s capacity, the capacity will automatically increase. Therefore, in order to add/remove elements from the slice without exceeding its capacity, we first check whether its length, len(s), is equal to the capacity, cap(s).