Golang Make and New Keywords
Overview
Keywords are unique reserved words that are used by a language. These special words are used to perform special operations in Golang. In this article, we will learn about new and made in Golang and implement some examples with them.
Introduction
If you have started learning golang then it's very obvious that you must be aware of Golangs keywords. Golang's Keywords that we will be learning today are used for the instantiation of items.
What is the "make" Keyword?
"make" in Golang is a keyword that is used to initialize only slices, maps, and channels. Unlike the new keywords, it does not return the pointer to the item. It initializes the data in memory with zero value.
Example:
In a case where the slice is created with the make keyword, the underlying array will be created and memory will be assigned to it with a specified length and capacity.
What is a "new" Keyword?
"new" in Golang is a keyword that is used to instantiate a struct (custom data type). The new keyword returns a pointer to the instantiated variable. It creates a "zeroed" storage for a new item.
Example:
In a case where we create a slice using a new keyword, the underlying array won't be created. thus new([]int) returns a pointer to nothing
What is the Difference between "make" and "new"?
- make in Golang is only used to allocate and initialize data of slice, map, and chan. new can assign any type of data(including slice, map, chan, and any custom struct)
- new returns a pointer of newly created data and make returns value of those.
- new just allocates memory, not initializes memory whereas make allocates and initializes memory.
Examples of "make"
Create Slice Using "make"
The below code shows how we can create slices. The first way to create a slice is based on parameters like length and capacity, giving us more flexibility. The second example creates a slice of a specified size.
Output:
Create Map Using "make"
Now let's create a map using the make keyword. We will first initialize the map and then assign values to it. Once a map is created we will add keys and values to it.
Output:
Create Channel Using "make"
Lastly, we will create a Golang Channel using make, once the channel is created we will add a message to it and later print it on the console.
Output:
Examples of "new"
Create Struct Using "new" Keyword
new returns a pointer to the struct. Each field inside the struct can then be accessed and modified.
We created a vehicle struct and later initialized it with the new keyword in golang. After the initialization, we assigned the values to the fields and later printed those to the console.
Output:
Conclusion
- We have an in-depth understanding of keywords in Golang and created different structs, channels, Maps, and, Slices with make and new keywords.
- There is a general thumb rule to use the make keyword for initializing slices, maps, and channels, and For arrays, structs, and all value types should be created using the new keyword.