Overview
The new and make in the go is always the novice more confusing things, I look very similar. But it is also very easy to explain the difference between the two.
The main features of new
First, the new is the built-in function, you can see it from the http://golang.org/pkg/builtin/here, and its definition is simple:
Copy Code code as follows:
The official document describes it as:
Copy Code code as follows:
The built-in function new is used to allocate memory, and its first argument is a type, not a value, and its return value is a pointer to the 0 value of the newly assigned type
Based on this description, we can implement a function similar to new:
Copy Code code as follows:
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 that begins with new, we should also return a pointer to the type for a convention.
Main features of Make
Make is also a built-in function, which you can see from http://golang.org/pkg/builtin/, which has a more than one parameter to define and a different return value:
Copy Code code as follows:
Func make (type, size Integertype) Type
The official document describes it as:
The built-in function make is used to allocate memory and initialize an object for the Slice,map or Chan type (note: Can only be used on these three types), like new, the first argument is a type instead of a value, unlike new, make returns a reference to the type rather than a pointer, and returns Values are also dependent on the type that is passed in, as specified below:
Copy Code code as follows:
Slice: The second parameter 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 you must not be smaller than the length value.
such as make ([]int, 0, 10)
Map: Allocates memory is initialized based on size, but the allocated map length is 0, and if size is ignored, a small memory is allocated when allocating memory is initialized
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 buffer.
Summarize
The role of new is to initialize a pointer to a type (*t) that is initialized for Slice,map or Chan and returns a reference (T).