Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make 和 new #53

Open
kevinyan815 opened this issue Feb 2, 2021 · 0 comments
Open

make 和 new #53

kevinyan815 opened this issue Feb 2, 2021 · 0 comments

Comments

@kevinyan815
Copy link
Owner

在 Go 语言中初始化一个结构时,可能会用到两个不同的关键字 — make 和 new。因为它们的功能相似,所以初学者可能会对这两个关键字的作用感到困惑,但是它们两者能够初始化的变量却有较大的不同。

  • make 的作用是初始化内置的数据结构,也就是我们在前面提到的切片、哈希表和 Channel
  • new 的作用是根据传入的类型分配一片内存空间并返回指向这片内存空间的指针

make

我们在代码中往往都会使用如下所示的语句初始化这三类基本类型,这三个语句分别返回了不同类型的数据结构

slice := make([]int, 0, 100)  // slice 是一个包含 data、cap 和 len 的结构体 reflect.SliceHeader
hash := make(map[int]bool, 10) // hash 是一个指向 runtime.hmap 结构体的指针
ch := make(chan int, 5) // ch 是一个指向 runtime.hchan 结构体的指针

new

相比与复杂的 make 关键字,new 的功能就简单多了,它只能接收类型作为参数然后返回一个指向该类型的指针:

i := new(int)

var v int
i := &v

上述代码片段中的两种不同初始化方法是等价的,它们都会创建一个指向 int 零值的指针。

type T struct {
  FieldA string
  FieldB int
}

t := new(T)

t2 := &T{}

上述代码都可以创建结构类型T的指针。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant