Golang:创建函数和第三个参数

huangapple go评论89阅读模式
英文:

Golang: Make function and third param

问题

以下是要翻译的内容:

这三种方式的区别是什么:

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

我知道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.

答案1

得分: 8

x := make([]int, 5) 创建一个长度为5、容量为5(与长度相同)的int类型切片。

x := make([]int, 5, 10) 创建一个长度为5、容量为10的int类型切片。

x := [5]int{} 创建一个长度为5的int类型数组。

切片

如果你需要使用append函数追加的元素超过切片的容量,Go运行时会分配一个新的底层数组,并将现有的元素复制到新数组中。因此,如果你知道切片的预估长度,最好使用显式的容量声明。这会在开始时消耗更多的内存用于底层数组,但可以节省多次分配和数组复制的CPU时间。
你可以在Go playground上进行简单的测试,观察lencapappend时如何变化。
每当cap值改变时,都会分配一个新的数组。

数组

数组的大小是固定的,所以如果你需要扩展数组,你必须创建一个新的数组,并将旧数组自己复制到新数组中。

关于Go中切片和数组有一些很好的文章:

英文:

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

答案2

得分: 1

第二行将在最开始分配10个int的内存,但返回给你的是一个包含5个int的切片。第二行并不占用更少的内存,如果你需要将切片扩展到不超过10 * load_factor的大小,它将为你节省另一个内存分配。

英文:

The second line will allocate 10 int's worth memory at the very beginning, but returning you a slice of 5 int's. The second line does not stand less memory, it saves you another memory allocation if you need to expand the slice to anything not more than 10 * load_factor.

huangapple
  • 本文由 发表于 2015年9月4日 14:07:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/32391147.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定