Hi,你们好,我是明哥。git
在本身学习 Golang 的这段时间里,我写了详细的学习笔记放在个人我的微信公众号 《Go编程时光》,对于 Go 语言,我也算是个初学者,所以写的东西应该会比较适合刚接触的同窗,若是你也是刚学习 Go 语言,不防关注一下,一块儿学习,一块儿成长。github
个人在线博客:golang.iswbm.com 个人 Github:github.com/iswbm/GolangCodingTimegolang
在官方文档中,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 只能传递一个参数,该参数为一个任意类型,能够是Go语言内建的类型,也能够是你自定义的类型数组
那么 new 函数到底作了哪些事呢:微信
举个例子函数
import "fmt"
type Student struct {
name string
age int
}
func main() {
// new 一个内建类型
num := new(int)
fmt.Println(*num) //打印零值:0
// new 一个自定义类型
s := new(Student)
s.name = "wangbm"
}复制代码
在官方文档中,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.ui
func make(t Type, size ...IntegerType) Typespa
翻译一下注释内容
注意,由于这三种类型是引用类型,因此必须得初始化(size和cap),可是不是置为零值,这个和new是不同的。
举几个例子
//切片
a := make([]int, 2, 10)
// 字典
b := make(map[string]int)
// 通道
c := make(chan int, 10)复制代码
new:为全部的类型分配内存,并初始化为零值,返回指针。
make:只能为 slice,map,chan 分配内存,并初始化,返回的是类型。
另外,目前来看 new 函数并不经常使用,你们更喜欢使用短语句声明的方式。
a := new(int)
a = 1
// 等价于
a := 1复制代码
可是 make 就不同了,它的地位无可替代,在使用slice、map以及channel的时候,仍是要使用make进行初始化,而后才能够对他们进行操做。
系列导读
24. 超详细解读 Go Modules 前世此生及入门使用