This is a created article in which the information may have evolved or changed.
Go has two mechanisms for allocating memory, the rules are simple, here is a brief introduction.
1. New function
The New () function can allocate memory for data of a value type (not knowing what value type goes to the section of the slice), and returns an initialized memory block pointer when the call succeeds, and the type is initialized to a value of 0, the prototype defines:
Func new (type) * type
New is a built-in function that allocates memory, but unlike the work done by new in other languages, it simply zeroed out the memory instead of initializing it.
2. Make function
The make () function is used to allocate memory space for reference types, such as: slice,map,channal, and so on, it is important to note that make () creates an object of reference type, not a pointer to a memory space. Make () function prototype:
Func make (type,size integertype) Type
The parameter type must be a reference type (slice,map,channal), and the parameter integertype specifies the number of objects to be created. Unlike new, make call success is a pointer that returns an object instead of a memory space.
The role of new is to initialize a pointer to a type (*T), which is initialized for Slice,map or Chan and returns a reference (T)
Package Main
Import (
"FMT"
)
Func Main () {
P: = new ([]int)
Fmt. PRINTLN (p)//output &[],p itself is an address
S: = make ([]int, 1)
Fmt. PRINTLN (s)//output [0],s itself is a slice object whose content defaults to 0
}
This example shows that when initializing the Slice,map and channel, using make is better than the new method, while the other forms are initialized with new.