Coming to Go from Ruby has been an experience and a half. A lot of the things I’ve stubbed my toes on are either vocabulary things, or things that I don’t know about because I’ve never really used a statically typed language before.
A map is a hash table is a ruby hash
Lets start by paying a visit to Wikipedia, the repository of all modern knowledge.
- Wikipedia on Maps
- Wikipedia on Hash Tables
- Ruby Hash class (jk, this one isn’t wikipedia).
Default values are unexpected
In Go, some types have a default value (probably to deal with the whole static typing thing???). For example, the default value of a boolean is
Similarly, ints also have a default value of 0.
So if I initialize a map of strings and ints, I get a number back, even if that key doesn’t exist in the map.
Multiple returns strike again
To solve the default value problem, Go offers optional multiple returns when querying a map/hash.
Now, when I query the map, I can then check the value of
ok, which will return
false if the key didn’t actually exist in the map.
The multiple return collection is optional. If I remove the
ok assignment, Go will not complain.
make() vs literal syntax
There are two ways to initialize a map. You can use the
Or you can use the ‘literal’ syntax, which I’ve used the the previous examples. Arbitrarily, I like the literal syntax. Maybe I just like curly braces.