new和make

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初始化

newThe built-in function new takes a type T and returns a value of type *T. The memory [pointed to] is initialized as described in the section on initial values.

零值

0""falsenil

使用示例(new也可以为数组分配内存)

 a := new(int)
 fmt.Printf("类型为:%T, 值为:%v\n", a, a)
 fmt.Printf("类型为:%T, 值为:%v\n", *a, *a)
 b := new(string)
 fmt.Printf("类型为:%T, 值为:%v\n", b, b)
 fmt.Printf("类型为:%T, 值为:%v\n", *b, *b)
 c := new(*int)
 fmt.Printf("类型为:%T, 值为:%v\n", c, c)
 fmt.Printf("类型为:%T, 值为:%v\n", *c, *c)
 
 运行结果:
 类型为:*int, 值为:0xc0000a6058
 类型为:int, 值为:0               
 类型为:*string, 值为:0xc000088220
 类型为:string, 值为:             
 类型为:**int, 值为:0xc0000ca020  
 类型为:*int, 值为:<nil>  

new(struct)和&struct{}区别

struct{}&struct{}new(struct)
new&struct{}
func main(){
	A := new(struct) // 只能返回一个struct的指针
	B := &struct{Id:1,Name:"张三"} // 可以返回一个带有默认值的struct的指针
}

上述例子就很好的说明了这个问题。

小结
newnewnewnew

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. The specification of the result depends on // the type:
func make(t Type, size ...IntegerType) Type
make(slice/map/channel)newmakemake
makenewchan、mapslice

简述make的初始化(slice/map/channel)

在这里插入图片描述

makeslice/map/channelmakeOMAKEMAKESLICE、OMAKEMAP、OMAKECHAN

使用示例

var a []int
fmt.Println(a[0])
// 运行结果
panic: runtime error: index out of range [0] with length 0

如果不对切片进行初始化,就无法使用

 var a []int
 a = make([]int, 1)
 fmt.Println(a[0])
mapchanmapmap0mapchannel

总结:

makenew
newint、string、数组makeslice、map、channelnewmakenewmakenew
newmakeslice,map,和channelnew

参考资料

go语言中文网
深入学习golang