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)
.
Subscribe to my newsletter
Read articles from Alissa Lozhkin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Alissa Lozhkin
Alissa Lozhkin
My name is Alissa and I am a fourth-year computer science and math student at the University of Toronto! I am very interested in computer science and software development, and I love learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin