This is a creation in Article, where the information may have evolved or changed.
http://se77en.cc/2014/04/25/the-difference-between-function-new-and-make-in-golang/
Overview
The Go language new
and make
has always been the novice more easily confused things, I look very similar. But explaining the difference between the two is also very easy.
Key features of new
The first new
is the built-in function, you can see it from http://golang.org/pkg/builtin/#new here, and its definition is simple:
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, and its return value is a pointer to the new assigned type 0 value
Based on this description, we can implement a similar new
function ourselves:
123456 |
func newint () *int { varint return &i}someint: = Newint () |
Our function is identical to the function someInt := new(int)
. So when we define our own functions that start with new, we should also return pointers to types for conventions.
Key features of Make
make
is also a built-in function, you can see it from http://golang.org/pkg/builtin/#make here, its definition is new
more than one parameter, the return value is also different:
The official documentation describes it as:
The built-in function is make
used to slice
map
allocate memory for, or type, chan
and initialize an object ( Note : Only available on these three types), new
like, the first parameter is also a type instead of a value, new
unlike the make
returns a reference to a type other than a pointer, and the return value depends on the type that is passed in, as described below:
1234567 |
The size specifies its length, and its capacity and length are the same. You can pass in the third parameter to specify a different capacity value, but must not be smaller than the length value. such as make ([]int0size0size0 or ignore capacity, pipeline is no buffer |
Summarize
new
The function of initializing a pointer to a type ( *T
) make
is to initialize slice
map
chan
and return a reference ( T
).