關鍵字make和new的區別
new
new分配空間,傳遞給new函數的參數是一個類型,返回值是指向這個新分配的零值的指針
函數原型
func new(Type)*Type
使用new函數爲變量分配內存空間
參數:new接收參數type
返回值:返回類型的指針,指針指向分配類型的內存地址
//爲默認數據類型分配空間
var num *int
num = new(int)
//爲自定義類型分配空間
type Student struct{
name string
age int
}
var stu *Student
stu = new(Student)
make
channel、map、slice類型是引用類型,make用於分配內存,但返回的類型就是這三個類型的引用,而不是指針
函數原型
func make(Type,size_Type)Type
參數:類型、長度
返回值:引用類型
如下栗子:
//只聲明但未初始化
var s1 []int
if s1 == nil {
fmt.Printf("s1 is nil \n")
}
//聲明並用make函數初始化,指定長度爲0
s2 := make([]int, 0)
if s2 ==nil{
fmt.Printf("s2 is nil ---%#v \n",s2)
}else{
fmt.Printf("s2 is not nil ---%#v \n",s2)
}
//聲明並用make函數初始化,指定長度爲3
s3 := make([]int, 3)
if s3 == nil{
fmt.Printf("s3 is nil ---%#v \n",s3)
}else{
fmt.Printf("s3 is not nil ---%#v\n",s3)
}
對比make和new
var s1 = new(map[int]string)
if *s1 == nil{
fmt.Printf("s1 is nil --- %#v \n",s1)
}
s2 := make(map[int]string)
if s2 == nil{
fmt.Printf("s2 is nil ---%#v \n",s2)
}else{
fmt.Printf("s2 is not nil --- %#v \n",s2)
}
make和new主要區別:
- make只能用來分配及初始化類型爲slice、map、channel的數據,即創建它們的數據結構;new可以分配任意類型的數據
- new分配返回的是指針;make返回引用
- new分配的空間被清零;make分配空間後會進行初始化