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 函數為變量分配內存空間。
var sum *int sum = new(int) //分配空間 *sum = 98 fmt.Println(*sum)
type Student struct { name string age int } var s *Student s = new(Student) //分配空間 s.name ="dequan" fmt.Println(s)
panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x80bd277] goroutine 1 [running]:
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 函數只用於 map,slice 和 channel,並且不返回指針。如果想要獲得一個顯式的指針,可以使用 new 函數進行分配,或者顯式地使用一個變量的地址。
Go語言中的 new 和 make 主要區別如下:- make 只能用來分配及初始化類型為 slice、map、chan 的數據。new 可以分配任意類型的數據;
- new 分配返回的是指針,即類型 *Type。make 返回引用,即 Type;
- new 分配的空間被清零。make 分配空間后,會進行初始化;