1. Computing

Programming Golang Tutorial Eight

Using Maps

By

If you've come here first, start with the first Golang Tutorial One or Golang tutorial two on arrays, tutorial three on slices and tutorial four on pointers and structs.

In the previous Golang tutorial on function methods, I looked at function methods. In this tutorial, I'll look at maps which let you access elements through a dictionary.

Don't know anything about Go? Here is an overview of Go.

This tutorial is about using Maps in Golang (aka Google Go). If you've found this you can see the other tutorials in the series, starting with the first.

A Map is a reference type that looks like a single dimension array or list. Other programming languages call them associative arrays or dictionaries. You use them with the general syntax:

map[key] = value

Note that the key can be an int, a float, complex number, string, pointer, even an interface that supports equality. We'll look at interfaces in a future tutorial.

Let's Make a Map!

Like slices, you can't just use the built in function new with maps, you use make instead as in this generic statement:

mymap := make(map[key type] value type)

Here's an example of a map in use. I've declared the map type friends explicitly so I can use that type as it simplifies the syntax. If I didn't use it then the first line in main() in the example below would be:

gang := make(map[string] int,5)

Here is the full example:

package main

import "fmt"

type friends map[string] int

func main() {
    gang := make(friends,5)
    gang["fred"]= 12
    gang["jimmy"]= 13
    gang["sara"] = 14
    gang["fagin"] = 65
    fmt.Println(gang)
}

This outputs:

map[sara:14 jimmy:13 fred:12 fagin:65]

How Many Elements in a Map?

Count them using len.

Add this to the first example after the fmt.Println(gang) line

fmt.Println(len(gang))

That outputs 4.

No Make Needed with Maps

In the first example substitute this for the gang := make line.

gang := friends {"burt" : 1, "ella" : 2}

This does an implicit make, and starts gang with two members. Then the others (fred.. fagin) are added making the gang six in size.

Assigning to a map entry creates that entry if it doesn't exist. Like adding one to fagin's age.

gang["fagin"] += 1

You can also refer to nonexistent members, and it won't crash. It just returns the default value for an int which is 0.

fmt.Println(gang["Keyser Soze"])
fmt.Println(gang)

But as that example shows, it won't add Keyser Soze in either. BTW if the name Keyser Soze means nothing to you, Google for The Usual Suspects.

Does the element exist?

It's possible to distinguish between returning the default value and returning if an element was found with this logic. The _ is the returned value which is thrown away. The boolean value foundhim is set to false if the index isn't present.

_, foundhim := gang["Keyser Soze"]

Iterating Through a Map.

Remember all maps have an index for each value. Sometimes we are interested in the index, sometimes the value and sometimes both. We can use the for statement to do this:

package main

import "fmt"

type friends map[string] int

func main() {
    gang := friends {"burt" : 1, "ella" : 2}
    gang["fred"]= 12
    gang["jimmy"]= 13
    gang["sara"] = 14
    gang["fagin"] = 65

    for name,age := range( gang ) {
        fmt.Println(name, age)
    }
}

This outputs:

sara 14
burt 1
ella 2
fagin 65
fred 12
jimmy 13

Note there is no order to elements. Maps are an unordered group of elements. Behind the scenes, I'm guesing it uses a hash function and that is why the elements are unordered.

Removing Elements from a Map

The classic issue with most programming languages that support iteration ithrough lists is that you should never delete list elements in a loop but it actually works in Go 1.

package main

import "fmt"

type friends map[string]int

func main() {
    gang := friends{"burt": 1, "ella": 2}
    gang["fred"] = 12
    gang["jimmy"] = 13
    gang["sara"] = 14
    gang["fagin"] = 65

    for name, age := range gang {
        if age == 14 {
            delete(gang,name)
            fmt.Println("Deleted ",name, age)
        }
    }
    fmt.Println(gang)
}

In the next Google Go tutorial 9, I'll look at interfaces and explain how to use them.

  1. About.com
  2. Computing
  3. C / C++ / C#
  4. All about Google Go
  5. Learn to program Go Tutorial Eight - Using maps

©2014 About.com. All rights reserved.