Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use make vs inline slice initializer?

Tags:

slice

go

Consider the following two snippets of code:

// Declaring the values inline.
os_list := []string{"Mac OSX", "Linux", "Windows 7"}
fmt.Println(os_list)

// Appending them to an empty slice.
os_list_two := make([]string, 3)
os_list_two = append(os_list_two, "Mac OSX", "Linux", "Windows 7")
fmt.Println(os_list_two)

When should we use one or the other?

like image 862
sergserg Avatar asked Feb 15 '23 10:02

sergserg


1 Answers

make will allocate and initialise memory for the string slice. In your example os_list_two contains three empty strings at indexes 0-2, followed by the items "Mac OSX", "Linux", "Windows 7". In the end you have a slice with six elements, not three as you probably expected.

You can see it illustrated here:
http://play.golang.org/p/Vm92dz8LqF

More on make:
http://golang.org/ref/spec#Making_slices_maps_and_channels

And on slices:
http://blog.golang.org/go-slices-usage-and-internals

Use make when you know beforehand how big a slice you need, or you need to index the slice at specific positions, or if the zero-values are in some way useful to you. If you just need a slice to append items to, you can simply define it using []string{}. It can also make sense not to use make if you need to initialise the slice with specific values, like you did for os_list.

like image 63
Robert Kajic Avatar answered Mar 12 '23 15:03

Robert Kajic