In Go, both make and new are built-in functions used for allocating memory, but they have important differences in their purpose and behavior.
new Function
The new function allocates memory for a new variable of a specified type and returns a pointer to that memory. The newly allocated memory is initialized to the zero value of the type. new can be used for any Go type, including basic types, composite types, pointers, and interfaces.
For example, if you want to create a pointer of type int and initialize it to its zero value, you can use new:
goptr := new(int) fmt.Println(*ptr) // Output: 0
make Function
The make function is used exclusively for initializing three reference types in Go: slices, maps, and channels, and returns an initialized (non-zero) value. This is because these types point to data structures that require initialization to function correctly. make not only allocates memory but also initializes related properties, such as the length and capacity of slices, the size of maps, and the buffer size of channels.
For example, to create a slice with an initial capacity, you can use make:
gos := make([]int, 0, 10) fmt.Println(len(s), cap(s)) // Output: 0 10
Summary
newallocates memory and returns a pointer to it, with the memory initialized to the zero value of the type, applicable to all types.makeis used for initializing slices, maps, and channels, and performs specific initialization beyond memory allocation, applicable only to these three types.
By utilizing these functions, Go provides a more flexible and efficient approach to memory management.