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 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 github训练的模型参数无法下载
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式
  • ¥15 关于#python#的问题:功能监听网页
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题