When to use make vs built-in slice initializer?

Consider the following two code fragments:

// 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?

+4
source share
2 answers

makewill allocate and initialize memory for the string fragment. In your example, it os_list_twocontains three blank lines at indexes 0-2, followed by the elements "Mac OSX", "Linux", "Windows 7". As a result, you have a slice with six elements, not three, as you expected.

Here you can see it:
http://play.golang.org/p/Vm92dz8LqF

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

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

make, , , , . , []string{}. make, , , os_list.

+10

. inline - , . , (, ), .

-2

All Articles