Go語言中new和make的區別


Go語言中new跟make是內置函數,主要用來創建分配類型內存。

new( )

new(T)創建一個沒有任何數據的類型為T的實例,並返回該實例的指針;

源碼解析

func new
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, args)只能創建 slice、map和channel,並且返回一個有初始值args(非零)的T類型的實例,非指針。

源碼解析

func make
func make(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, 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.

二者異同

二者都是內存的分配(堆上),但是make只用於slice、map以及channel的初始化(非零值);而new用於類型的內存分配,並且內存置為零。所以在我們編寫程序的時候,就可以根據自己的需要很好的選擇了。

make返回的還是這三個引用類型本身;而new返回的是指向類型的指針。

作者:子恆|haley
出處:http://www.haleyl.com
交流溝通:QQ群866437035
在這里插入圖片描述


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM