1.new方法
源码中的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
示例代码:
a := new(int) //申请指定类型的一块空间,并且返回一个指向该类型内存地址的指针 fmt.Println(*a) //同时会把分配的内存地址的变量值置为类型的零值,此处结果为0 *a = 1 //对该指针对应的值赋值 fmt.Println(*a) //结果为1
总结: 它只接受一个参数,这个参数是一个类型,分配好内存后,返回一个指向该类型内存地址的指针。同时会把分配的内存地址的变量值置为类型的零值
2.make方法
源码中的make方法
func make(t Type, size ...IntegerType) Type
示例代码
arr := make([]int, 10) //创建切片 fmt.Println(arr) //[0 0 0 0 0 0 0 0 0 0] fmt.Printf("%T\n", arr) //[]int fmt.Printf("%p\n", arr) //内存地址 0xc00001e0a0
make也是用于内存分配的,但是和new不同,它只用于chan、map以及切片的内存创建,而且它返回的类型就是这三个类型本身,
而不是他们的指针类型,因为这三种类型就是引用类型,所以就没有必要返回他们的指针了
一句话来说明:
make返回的还是这三个引用类型本身;而new返回的是指向类型的指针。
原文:https://www.cnblogs.com/weisunblog/p/12696763.html