doubaomao9304 2015-02-20 18:56
浏览 359
已采纳

go语言的make()功能的目的是什么?

I'm learning golang, and confused about the capacity in slice.
For example arr := make([]float64, 5, 10)
I have an array of 5 values, and its capacity is 10. If I assign a value to 8th position, the compiler would throw an error index is out of range. If I grow a slice, but it creates a new slice (see the doc that I copied from the official go language).

Here's the slice doc:

"Slicing does not copy the slice's data. It creates a new slice value that points to the original array." "To increase the capacity of a slice one must create a new, larger slice and copy the contents of the original slice into it. "

So what's the purpose of capacity?

Thanks

  • 写回答

1条回答 默认 最新

  • dongshou7903 2015-02-20 19:26
    关注

    A slice has three parts. A pointer to an underlying array, a length, and a capacity. The length is the length of the array according to program logic and capacity is the true length of the underlying array.

    The capacity is fixed without reallocating. The length can be changed whenever you want as long as the final length doesn't exceed the capacity. In this case you can do arr[:7] and your array will be length 7 but still capacity 10. If you do arr[:11], you will get an error because you can't grow the slice that large without reallocating.

    You may want to read this for a more in depth discussion of slices: http://blog.golang.org/go-slices-usage-and-internals

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥66 比特币地址如何生成taproot地址
  • ¥20 数学建模数学建模需要
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决