Easy map and slice declarations in Go



In Go there are a couple of variable declaration syntaxes. Go uses type inference, so you don’t have to repeat yourself. Maps (hash tables; dictionaries), and slices (views onto arrays) always felt clumsy to me, because they use the make() function. I’m also a fan of using the := declaration-and-assignment syntax most of the time, as opposed to explicit variable declarations:

myMap := make(map[string]float64)
mySlice := make([]string, 0)

I don’t know when I learned this, but you can use an empty initializer to declare and initialize a variable at once. It’s a little less typing and feels and looks cleaner to me:

myMap := map[string]float64{}
mySlice := []string{}

This works because it’s an empty form of the syntax for declaring and filling a variable with values at the same time, e.g. you can add in initial values as follows:

myMap := map[string]float64{
"var1": 123,
"var2": 456,

Leaving out the initial values, you end up with empty curly braces {} which initializes the variable without any contents. This is especially helpful for constructing values to pass to functions, such as a function that takes a map of optional this-and-that but you don’t have anything to give it:

result := someFunc(1, “two”, map[string]float64{})

That syntax is a much cleaner replacement for the way I did it previously:

throwawayMap := make(map[string]float64)
result := someFunc(1, "two", throwawayMap)

Do you have any further tips and tricks? Let me know in the comments, or tweet to @xaprb!

Published by Baron Schwartz
comments powered by Disqus