// 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 函數會把分配的記憶體置為零,也就是型別的零值。
var sum *int sum = new(int) //分配空間 *sum = 98 fmt.Println(*sum)當然,new 函數不僅僅能夠為系統預設的資料型別,分配空間,自定義型別也可以使用 new 函數來分配空間,如下所示:
type Student struct { name string age int } var s *Student s = new(Student) //分配空間 s.name ="dequan" fmt.Println(s)這裡如果我們不使用 new 函數為自定義型別分配空間(將第 7 行注釋),就會報錯:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x80bd277]
goroutine 1 [running]:
// 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 主要區別如下: