GO语言中make与new的区别
区别
- 1 make不仅分配内存,还会初始化。 new只会分配零值填充的值
- 2make只适用slice,map,channel的数据,new 没有限制
- 3make返回原始类型(T),new返回类型的指针(*T)
源码中定义的区别
func make(t Type,size …IntegerType) Type
func new(Type) *Type
func main() {
//声明切片slice1并申请地址,为申请的10个元素都赋上元素类型的零值
var slice1 = make([]int, 10)
fmt.Println(slice1, len(slice1), cap(slice1)) //10 10
var slice2 = new([]int)
fmt.Println(slice2, len(*slice2), cap(*slice2))
s1 := make([]int, 0)
fmt.Println("s1", len(s1), cap(s1))
s2 := new([]int)
s3 := *new([]int)
var s4 []int
var s5 = []int{}
//
fmt.Println("s1 is nil?", s1 == nil) //false
fmt.Println("s2 is nil?", *s2 == nil) //true
fmt.Println("s3 is nil?", s3 == nil) //true
fmt.Println("s4 is nil?", s4 == nil) //true
fmt.Println("s5 is nil?", s5 == nil) //false
a1 := *new([10]int)
a2 := [10]int{}
fmt.Println(a1, a2)
}
总结
new 可以为任何类型的值开辟内存并返回此值的指针
new申请的值均为零值,对创建映射和切处没有意义
实际工作中通常使用字面量来创建数组而很少使用new