Overview
New and make in the Go language have always been things that newcomers are more likely to be confused about, and they look very similar at first glance. However, it is also very easy to explain the difference between the two.
The main characteristics of new
First of all, new is a built-in function, you can/pkg/builtin/#newSeeing it here, its definition is also very simple:
func new(Type) *Type
The official documentation describes it as:
The built-in function new is used to allocate memory. Its first parameter is a type, not a value. Its return value is a pointer to the zero value of the newly allocated type.
Based on this description, we can implement a new-like function ourselves:
func newInt() *int {
var i int
return &i
}
someInt := newInt()
The function of our function is exactly the same as someInt := new(int). So when we define a function starting with new ourselves, we should also return a pointer of type for convention.
The main features of make
make is also a built-in function, you can use it from/pkg/builtin/#makeSee it here. It has one more parameter than new and the return value is also different:
func make(Type, size IntegerType) Type
The official documentation describes it as:
The built-in function make is used to allocate memory and initialize an object for slice, map or chan types (note: it can only be used on these three types). Similar to new, the first parameter is also a type instead of a value. Unlike new, make returns a reference to the type rather than a pointer, and the return value also depends on the specific type passed in. The specific description is as follows:
Slice: The second parameter size specifies its length, and its capacity and length are the same.
You can pass in a third parameter to specify different capacity values, but it must not be smaller than the length value.
For example make([]int, 0, 10)
Map: Initialize allocated memory according to size, but the allocated map length is 0. If size is ignored, a small size memory will be allocated when initializing allocated memory.
Channel: The pipeline buffer is initialized according to the buffer capacity. If the capacity is 0 or the capacity is ignored, the pipeline has no buffers
Summarize
The function of new is to initialize a pointer to the type (*T), and make is to initialize slice, map or chan and return a reference (T).