new(Point)&oint OK&oint / Combines allocation and initializationnew(int)&int // Illegal// Works,but it is less convenient to write than new(int)var i int&i/ G* ^' r) _" l: A; D$ H& }
通过查看以下示例可以看出new和之间的区别make:" P' G- r0 X! l7 B P" Z6 y5 X) A
p := new(chan int) // p has type: *chan intc := make(chan int) // c has type: chan int( Z7 J2 h2 E2 ~ ?4 W$ c
假设 Go 没有newand make,但它具有内置函数NEW。示例代码将如下所示:* S E& Y7 h4 R& G9 t
p := NEW(*chan int) // * is mandatoryc := NEW(chan int)# l, v0 U; R2 S- e$ N# L8 a' _6 w
该* 会是强制性的,所以:, E1 M1 h) Y: m/ L! ~
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 ) I# p' Y$ K" F. P+ ^2 _9 K
是的,可以new和合并make单个内置函数。然而,与两个内置函数相比,单个内置函数可能会导致新 Go 程序员更困惑。$ i" d6 |3 t2 M7 u3 E- k
考虑到上述所有要点,似乎更合适new并make保持分离。