喵-见缝插针 2015-03-20 10:27 采纳率: 0%
浏览 1037
已采纳

初始化空片的正确方法

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 maixpy训练模型,模型训练好了以后,开发板通电会报错,不知道是什么问题
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容