小编典典

new()和make之间的区别

go

引入文件奉献许多段落解释之间的区别new()make(),但在实践中,您可以创建本地范围内的物体并返回它们。

为什么要使用这对分配器?


阅读 192

收藏
2021-11-02

共1个答案

小编典典

Go 有多种内存分配和值初始化的方式:

&T{...}`, `&someLocalVar`, `new`,`make

创建复合文字时也可能发生分配。


new可用于分配诸如整数之类的值,&int是非法的:

new(Point)
&Point{}      // OK
&Point{2, 3}  // Combines allocation and initialization

new(int)
&int          // Illegal

// Works, but it is less convenient to write than new(int)
var i int
&i

通过查看以下示例可以看出new和之间的区别make

p := new(chan int)   // p has type: *chan int
c := make(chan int)  // c has type: chan int

假设 Go 没有newand make,但它有内置函数NEW。然后示例代码将如下所示:

p := NEW(*chan int)  // * is mandatory
c := NEW(chan int)

* 会是强制性的,所以:

new(int)        -->  NEW(*int)
new(Point)      -->  NEW(*Point)
new(chan int)   -->  NEW(*chan int)
make([]int, 10) -->  NEW([]int, 10)

new(Point)  // Illegal
new(int)    // Illegal

是的,可以将new和合并make为单个内置函数。然而,与拥有两个内置函数相比,单个内置函数可能会导致新 Go 程序员更困惑。

考虑到上述所有要点,似乎更适合newmake保持分离。

2021-11-02