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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With