golang 中有两个内存分配机制 :new和make,二者有明显区别.
new:new(T)分配了零值填充的T类型的内存空间,并且返回其地址,即一个*T类型的值。其自身是一个指针.可用于初始化任何类型
make: 返回一个有初始值(非零)的T类型,而不是*T,其只能用来初始化:slice,map和channel三种类型。
对比:
- 适用范围:make 只能创建内建类型(slice map channel), new 则是可以对所有类型进行内存分配
- 返回值: new 返回指针, make 返回引用
- 填充值: new 填充零值, make 填充非零值
代码:
package main import ( "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 }
有疑问加站长微信联系(非本文作者)