Skip to main content

Introduction to Go's Make Function

Updated 1 min readMarkdown

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).

About the author

  • My name is Alissa and I am a software developer at RBC Capital Markets! I studied computer science and math at the University of Toronto and I am very interested in learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin

No comments yet. Be the first to comment.

More from this blog