Notes on Go, part 7 of ∞

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.

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 false.

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 make() syntax:

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.

Resources

A Tour of Go
Go maps in action
Go By Example
Effective Go

Leave a Reply

Your email address will not be published. Required fields are marked *