旧行李 2015-03-20 10:27 采纳率: 25%
浏览 235
已采纳

初始化空片的正确方法

To declare an empty slice, with a non-fixed size, is it better to do:

mySlice1 := make([]int, 0)

or:

mySlice2 := []int{}

Just wondering which one is the correct way.

转载于:https://stackoverflow.com/questions/29164375/correct-way-to-initialize-empty-slice

  • 写回答

4条回答 默认 最新

  • 笑故挽风 2015-03-20 10:38
    关注

    The two alternative you gave are semantically identical, and I would assume they produce the same assembly instructions.

    To avoid an unnecessary allocation, in case you will end up not using the slice, you can leave it with a nil value:

    var myslice []int
    

    As written in the Golang.org blog:

    a nil slice is functionally equivalent to a zero-length slice, even though it points to nothing. It has length zero and can be appended to, with allocation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型