From Ruby to Golang — Hash and Maps

Joel Bryan Juliano
1 min readJun 27, 2018

--

If you need to store amounts of data programatically in Go, that you can conveniently retrieve by its name and not by its index, then use a map.

A map is a storage of records that can be retrieved by using a key which is mapped to a value. It is a good way to organise information that can be retrieved later.¹

Coming from Ruby, a map‘s equivalent is a hash. Hashes can either be created implicitly using {} or using Hash.new. Here's how hash is created in Ruby. First, we initialise an empty hash by assigning {} to a variable named basket, then we iterate the contents and print the key name and it’s value.

In order for us to replicate this example in Go, we would use Go’s built-in keyword called map and place it into a variable that maps a unique name to a value.

But before we proceed on creating a map, we would need to understand two ways to initialise and allocate a map. By declaration, being able to initialise and allocate later, and by assignment, a one-liner way to initialise and allocate a map.

Read the remaining chapter from the book “From Ruby to Golang: A Ruby Programmer’s Guide to Learning Golang” available at https://leanpub.com/rb2go

--

--