make 和 new
new函数
作用
- 分配内存
- 设置零值
- 返回指针
eg:
type Student struct{
name string
age int
}
func main(){
//new 一个内建类型
num := new(int)
fmt.Println(*num) //打印:0
//new一个自定义类型
s := new(Student)
s.name = "yx"
fmt.Println(s.name) //yx
}
注:
目前来看new函数不常用,因为大家更喜欢用短语句声明的方式
a := new(int)
*a = 1
// 等价于
a := 1
make函数
作用
- 内建函数 make 用来为 slice,map 或 chan 类型(注意:也只能用在这三种类型上)分配内存和初始化一个对象
- make 返回类型的本身而不是指针,而返回值也依赖于具体传入的类型,因为这三种类型就是引用类型,所以就没有必要返回他们的指针了
- 注意,因为这三种类型是引用类型,所以必须得初始化(size和cap),但不是置为零值,这个和new是不一样的。
eg:
//切片
a := make([]int, 2, 10)
// 字典
b := make(map[string]int)
// 通道
c := make(chan int, 10)