Evgeniy Tkachenko
Evgeniy Tkachenko

Reputation: 1737

Golang: Make function and third param

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.

Upvotes: 4

Views: 524

Answers (2)

RoninDev
RoninDev

Reputation: 5676

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 Go playground
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

Upvotes: 9

user1663023
user1663023

Reputation:

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.

Upvotes: 1

Related Questions