Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: Make function and third param

Tags:

go

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.

like image 913
Evgeniy Tkachenko Avatar asked Aug 30 '25 18:08

Evgeniy Tkachenko


2 Answers

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

like image 92
RoninDev Avatar answered Sep 02 '25 19:09

RoninDev


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!