Kalan's Blog

Software Engineer / Taiwanese / Life in Fukuoka

Current Theme light

In golang, there are two reserved words: make and new. These are often confused when first learning golang. Here are some simple notes on them.

new

new is used to initialize a generic type and returns the memory address. Therefore, we usually use a pointer variable to receive the type after new. It is important to note that new automatically initializes the type with zeroed values. This means that strings will be "", numbers will be 0, and channels, functions, maps, slices, etc. will be nil.

Because of this feature, if we perform the following operation on a map, it will result in a panic: assignment to entry in nil map error:

func main() {
	people := new(map[string]string)
	p := *people
	p["name"] = "Kalan" // panic: assignment to entry in nil map
}

This is because the initialized map is a nil map and does not have default values like other primitive types.

If we use struct for initialization, we can also use & to represent the address. The following two methods have the same effect:

type Person struct {
  Name string
  Age  int
}

func main() {
    p := &Person{}
    p := new(Person)
}

The advantage of the first method is that the Person struct can be further customized according to the values we want to pass in, while new assigns zeroed values to all fields.

make

Unlike new, make is used to initialize special types such as channels, maps, slices, etc. It is important to note that make does not return a pointer. If you want to obtain a pointer, you need to consider initializing the type in a way similar to new.

func main() {
    receiver := make(chan string) // initializes a channel without returning a pointer
    person := make(map[string]string)
    people := make([]string, 100) // initializes a string array with a length of 100
}

Again, it must be emphasized that make does not return a pointer! The following code will throw an error:

func main() {
	person := make(map[string]string)
	fmt.Println(*person) // invalid indirect of person
}

Conclusion

make and new can be easily confused when starting to learn golang. Sometimes, when passing a pointer as an argument, we accidentally use make. It is important to understand the difference between these two.

Further Reading

Prev

Birthday Paradox

Next

Dynamically load modules via vuex and webpack dynamic import

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee

作者

Kalan 頭像照片,在淡水拍攝,淺藍背景

愷開 | Kalan

Hi, I'm Kai. I'm Taiwanese and moved to Japan in 2019 for work. Currently settled in Fukuoka. In addition to being familiar with frontend development, I also have experience in IoT, app development, backend, and electronics. Recently, I started playing electric guitar! Feel free to contact me via email for consultations or collaborations or music! I hope to connect with more people through this blog.