栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

new()和make之间的区别

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

new()和make之间的区别

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 没有

new
and
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
保持分离。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/647473.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号