There are two memory allocation mechanisms in Golang: New and make, which differ significantly from each other.
New:new (t) allocates a 0 value to the memory space of the type T, and returns its address, which is the value of a *t type. itself is a pointer. Can be used to initialize any type
Make: Returns a T type with an initial value (not 0), instead of *t, which can only be used to initialize: Slice,map and channel three types.
Contrast:
- Scope of application: Make can only create built-in types (slice map channel), and new is memory-allocated for all types
- Return value: New Returns a pointer, make returns a reference
- Padding value: New fills 0 values, make fills non 0 values
Code:
Package Mainimport ("FMT" "reflect") Type Booksstruct{Title, Content, Authorstring}func Main () {a:=New([]int) fmt. Println (a)//the output &[],a itself is an addressB: = make ([]int,1) fmt. Println (b)//The output [0],b itself is a slice object whose content defaults to 0Book1:=New(Books) Book1. Title="This is Book1 title"Book1. Content="This is Book1 content"Book1. Author="This is Book1 author"Book2:= books{"This is book2 title","This is book2 content","This is book2 author"} fmt. Println ("Book1:", Book1,", Type:", reflect. TypeOf (Book1))
//Book1: &{this is Book1 title This is Book1 content this is Book1 author}, Type: *main. BooksFmt. Println ("Book2:", Book2,", Type:", reflect. TypeOf (BOOK2))
//Book2: {This was Book2 title this is BOOK2 content of this is Book2 author}, Type:main. Books}