Go語言中有自動垃圾回收的機制(garbage collection),不需要為內存回收擔心。而內存分配的有兩種操作方式,new和make,本節重點講述這兩種操作方式。
new
內置函數new與其他語言類似,new(T)為T類型分配一個零空間,并返回其地址,即*T類型的值。或者換句話說,它返回一個指向新分配的T類型零值的指針,這一點需要牢記。
bytes.Buffer 的文檔指出“Buffer 的零值是一個可以使用的空緩沖區”。 同樣,sync.Mutex沒有顯式構造函數或Init方法。 相反,sync.Mutex 的零值被定義為未鎖定的互斥鎖。
參數定義
func new(Type) *Type
The new built-in function allocates memory. The first argument is a type, not a value, and the value returned is a pointer to a newly allocated zero value of that type.
make
內置的make(T)僅用于創建slices, maps和channels,返回類型T的初始化值(非零!),并且不是一個指針*T。產生這種區別的原因,是在使用前引用的數據類型必須進行初始化。
參數定義
func make(t Type, size ...IntegerType) Type
The make built-in function allocates and initializes an object of type slice, map, or chan (only). Like new, the first argument is a type, not a value. Unlike new, make's return type is the same as the type of its argument, not a pointer to it. The specification of the result depends on the type:
Slice: The size specifies the length. The capacity of the slice is equal to its length. A second integer argument may be provided to specify a different capacity; it must be no smaller than the length. For example, make([]int, 0, 10) allocates an underlying array of size 10 and returns a slice of length 0 and capacity 10 that is backed by this underlying array. Map: An empty map is allocated with enough space to hold the specified number of elements. The size may be omitted, in which case a small starting size is allocated. Channel: The channel's buffer is initialized with the specified buffer capacity. If zero, or the size is omitted, the channel is unbuffered.
區別
new只負責分配,make負責初始化,區別點:
- new(T)返回指針,*T指向零值T
- make(T)返回初始化后的T