dsgd4654674 2015-09-04 06:07 采纳率: 0%
浏览 282
已采纳

Golang:Make函数和第三个参数

What is the difference between:

   x := make([]int, 5, 10)    
   x := make([]int, 5)   
   x := [5]int{}

I know that make allocates an array and returns a slice that refers to that array. I don't understand where it can be used?

I can't find a good example that will clarify the situation.

  • 写回答

2条回答 默认 最新

  • dsf11t5u1651 2015-09-04 06:11
    关注

    x := make([]int, 5) Makes slice of int with length 5 and capacity 5 (same as length).

    x := make([]int, 5, 10) Makes slice of int with length 5 and capacity 10.

    x := [5]int{} Makes array of int with length 5.

    Slices

    If you need to append more items than capacity of slice using append function, go runtime will allocate new underlying array and copy existing one to it. So if you know about estimated length of your slice, better to use explicit capacity declaration. It will consume more memory for underlying array at the beginning, but safe cpu time for many allocations and array copying.
    You can explore how len and cap changes while append, using that simple test on <kbd>Go playground</kbd>
    Every time when cap value changed, new array allocated

    Arrays

    Array size is fixed, so if you need to grow array you have to create new one with new length and copy your old array into it by your own.

    There are some great articles about slices and arrays in go:
    http://blog.golang.org/go-slices-usage-and-internals
    http://blog.golang.org/slices

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

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失