According to https://play.golang.org/p/7RPExbwOEU they all print the same and have the same length and capacity. Is there a difference between the three ways to initialize a slice? Is there a preferred way? I find myself using both make([]int, 0)
and []int{}
with the same frequency.
make([] int,0),[] int {}和* new([] int)之间有什么区别?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
1条回答 默认 最新
- dqbh8054 2017-03-14 19:58关注
This initializes a 0 length slice.
make([]int, 0)
Using
make
is the only way to initialize a slice with a specific capacity different than the length. This allocates a slice with 0 length, but a capacity of 1024.make([]int, 0, 1024)
This is a slice literal, which also initializes a 0 length slice. Using this or
make([]int, 0)
is solely preference.[]int{}
This initializes a pointer to a slice, which is immediately dereferenced. The slice itself has not been initialized and will still be nil, so this essentially does nothing, and is equivalent to
[]int(nil)
*new([]int)
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 1无用
悬赏问题
- ¥100 set_link_state
- ¥15 虚幻5 UE美术毛发渲染
- ¥15 CVRP 图论 物流运输优化
- ¥15 Tableau online 嵌入ppt失败
- ¥100 支付宝网页转账系统不识别账号
- ¥15 基于单片机的靶位控制系统
- ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
- ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
- ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
- ¥15 手机接入宽带网线,如何释放宽带全部速度