Junior — Middle
Can you explain the differences between the new and make operators in Go language?
sobes.tech AI
Answer from AI
In Go, the operators new and make are used for memory allocation but apply to different types and have different purposes:
-
new(T) allocates memory for type T, initializes it with the zero value, and returns a pointer *T. It is used for all types but returns a pointer.
-
make(T, args...) is used only for initializing slices, maps, and channels. It returns an initialized value of type T (not a pointer).
Example:
p := new(int) // p is of type *int, points to 0
s := make([]int, 5) // s is a slice of length 5, ready to use
m := make(map[string]int) // initialized map
Summary:
- new allocates memory and returns a pointer.
- make initializes complex data structures and returns a value.