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条)

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?