golang中make与new的区别
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
总结:
- new 是一种内置函数,用来为各种内建类型分配内尺寸。这些内置类型可以任意,还可以new你自定义的struct类型。
- 为对应类型的零值分配一个内存。
- new函数返回的是一个指针。
例子
type Person struct {
name string
age int
}
func main() {
// new 一个任意的内建类型
num := new(int)
fmt.Println(*num) //打印值,是默认的零值
// new 一个自行定义的结构体类型
s := new(Person)
s.name = "张三"
}
make 函数
make官方文档描述:
//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.
func make(t Type, size ...IntegerType) Type
总结:
- make函数只能用在三种类型的创建上——slice、map、chan类型,内置函数为其分配内存和初始化一个对象。
- make 返回的是类型本身,而不是一个指针,返回的值的类型取决于你要创建的值,因为①中所提到的类型都是引用类型,所以本质上也没必要返回指针类型了。
- 这三种类型是引用类型,因此我们不是对其赋予0值,而是对其进行初始化。对于slice来说,make的第二个参数代表了切片的长度,因此必须赋值。
例子
//切片
a := make([]int, 20, 100)
// 字典
b := make(map[string]int)
// 通道
c := make(chan int, 5)
总结
new函数:为所有的类型分配内存,并初始化为零值,返回指针。
make函数:只能为 slice,map,chan 分配和初始化内存,返回的是类型。
此外, new 函数并不常用,大家更喜欢使用短语句声明的方式来代替用new来声明变量。
思考:可以用new来代替make来创建吗?
答案:可以的。
func main() {
a := *new([]int)
fmt.Printf("%T, %v\n", a, a==nil)
b := *new(map[string]int)
fmt.Printf("%T, %v\n", b, b==nil)
c := *new(chan int)
fmt.Printf("%T, %v\n", c, c==nil)
}
作者:陈双寅