Go 有多种内存分配和值初始化的方式:
&T{...}`, `&someLocalVar`, `new`,`make创建复合文字时也可能发生分配。
new可用于分配诸如整数之类的值,
&int是非法的:
new(Point)&Point{} // OK&Point{2, 3} // Combines allocation and initializationnew(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 intc := make(chan int) // c has type: chan int
假设 Go 没有
newand
make,但它有内置函数
NEW。然后示例代码将如下所示:
p := NEW(*chan int) // * is mandatoryc := 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) // Illegalnew(int) // Illegal
是的,可以将
new和合并
make为单个内置函数。然而,与拥有两个内置函数相比,单个内置函数可能会导致新 Go 程序员更困惑。
考虑到上述所有要点,似乎更适合
new并
make保持分离。



