golang 中有兩個記憶體配置機制 :new和make,二者有明顯區別.
new:new(T)分配了零值填充的T類型的記憶體空間,並且返回其地址,即一個*T類型的值。其自身是一個指標.可用於初始化任何類型
make: 返回一個有初始值(非零)的T類型,而不是*T,其只能用來初始化:slice,map和channel三種類型。
對比:
- 適用範圍:make 只能建立內建類型(slice map channel), new 則是可以對所有類型進行記憶體配置
- 傳回值: new 返回指標, make 返回引用
- 填儲值: new 填充零值, make 填充非零值
代碼:
package mainimport ( "fmt" "reflect")type Books struct { Title, Content, Author string}func main() { a := new([]int) fmt.Println(a) //輸出&[],a本身是一個地址 b := make([]int, 1) fmt.Println(b) //輸出[0],b本身是一個slice對象,其內容預設為0 book1 := new(Books) book1.Title = "this is book1 title" book1.Content = "this is book1 content" book1.Author = "this is book1 author" book2 := Books{"this is book2 title", "this is book2 content", "this is book2 author"} fmt.Println("book1:", book1, ",Type:", reflect.TypeOf(book1))
//book1: &{this is book1 title this is book1 content this is book1 author} ,Type: *main.Books fmt.Println("book2:", book2, ",Type:", reflect.TypeOf(book2))
//book2: {this is book2 title this is book2 content this is book2 author} ,Type: main.Books}