This is a creation in Article, where the information may have evolved or changed.
There are two memory allocation mechanisms in Golang: New and make, which differ significantly from each other.
NEW: Used to initialize an object and return the first address of the object. itself is a pointer. Can be used to initialize any type
Make: Returns an initialized instance, returning an instance, not a pointer, which can only be initialized: Slice,map and channel three types
- Package Main
- Import (
- "FMT"
- )
- Func Main () {
- A : = new ([]int)
- Fmt. Println (a)//output &[],a itself is an address
- b : = Make ([]int, 1)
- Fmt. PRINTLN (b)//output [0],b itself is a slice object whose content defaults to 0
- }
This example shows that when initializing Slice,map and channel, using make is better than new, while other forms are initialized with new.
Initialization
Initialization with new can only be done by default initialization and cannot be assigned a value. Many times, default initialization is not a good idea, such as a struct, the default value of the structure of the initialization is not much use, so in the face of struct initialization we generally apply the following methods:
- Type Rect struct {
- X, y float64
- width, height float64
- }
So we initialize the struct by adding the address symbol in front of the struct:
- Rect3 : = &rect{0, 0, .
- Rect4 : = &rect{width:100, height:200}
This initialization method is very common in initializing structs in Golang.