Go語言中 new 和 make 是兩個內置函數,主要用來創建並分配類型的內存。在我們定義變量的時候,可能會覺得有點迷惑,不知道應該使用哪個函數來聲明變量,其實他們的規則很簡單,new 只分配內存,而 make 只能用於 slice、map 和 channel 的初始化
new
在Go語言中,new 函數描述如下:
// 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. func new(Type) *Type
從上面的代碼可以看出,new 函數只接受一個參數,這個參數是一個類型,並且返回一個指向該類型內存地址的指針。同時 new 函數會把分配的內存置為零,也就是類型的零值。
make
make 也是用於內存分配的,但是和 new 不同,它只用於 chan、map 以及 slice 的內存創建,而且它返回的類型就是這三個類型本身,而不是他們的指針類型,因為這三種類型就是引用類型,所以就沒有必要返回他們的指針了。
在Go語言中,make 函數的描述如下:
// 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, so make([]int, 0, 10) allocates a slice of length 0 and // capacity 10. // 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. func make(t Type, size ...IntegerType) Type
通過上面的代碼可以看出 make 函數的 t 參數必須是 chan(通道)、map(字典)、slice(切片)中的一個,並且返回值也是類型本身。
注意:make 函數只用於 map,slice 和 channel,並且不返回指針。如果想要獲得一個顯式的指針,可以使用 new 函數進行分配,或者顯式地使用一個變量的地址。
Go語言中的 new 和 make 主要區別如下:
- make 只能用來分配及初始化類型為 slice、map、chan 的數據。new 可以分配任意類型的數據;
- new 分配返回的是指針,即類型 *Type。make 返回引用,即 Type;
- new 分配的空間被清零。make 分配空間后,會進行初始化;
make 關鍵字的主要作用是創建 slice、map 和 Channel 等內置的數據結構,而 new 的主要作用是為類型申請一片內存空間,並返回指向這片內存的指針。
