为什么我要 make() 或 new()? [英] Why would I make() or new()?
问题描述
介绍文档用了很多段落来解释new()
和make()
之间的区别,但在实践中,您可以在本地范围内创建对象并返回它们.
The introduction documents dedicate many paragraphs to explaining the difference between new()
and make()
, but in practice, you can create objects within local scope and return them.
为什么要使用这对分配器?
Why would you use the pair of allocators?
推荐答案
Go 有多种内存分配和值初始化的方式:
Go has multiple ways of memory allocation and value initialization:
&T{...}
、&someLocalVar
、new
、make
创建复合文字时也可能发生分配.
Allocation can also happen when creating composite literals.
new
可用于分配整数等值,&int
是非法的:
new
can be used to allocate values such as integers, &int
is illegal:
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
的区别可以看下面的例子:
The difference between new
and make
can be seen by looking at the following example:
p := new(chan int) // p has type: *chan int
c := make(chan int) // c has type: chan int
假设 Go 没有 new
和 make
,但它有内置函数 NEW
.然后示例代码将如下所示:
Suppose Go does not have new
and make
, but it has the built-in function NEW
. Then the example code would look like this:
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 程序员更加困惑.
Yes, merging new
and make
into a single built-in function is possible. However, it is probable that a single built-in function would lead to more confusion among new Go programmers than having two built-in functions.
考虑到以上所有几点,new
和 make
保持分开似乎更合适.
Considering all of the above points, it appears more appropriate for new
and make
to remain separate.
这篇关于为什么我要 make() 或 new()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!