A Golang map is a unordered collection of key-value pairs. For every key, there is a unique value. If you have a key, you can lookup the value in a map.

Sometimes its called an associative array or hash table. An example of a map in Go:

1
elements := make(map[string]string)

Its defines as a string to string mapping. In this example we’ll use the periodic elements.

You can map on other variable types too. Below an example of string to int mapping:

1
2
alpha := make(map[string]int)
alpha["A"] = 1

Map in golang

Map example

Create a new file named map.go, I like to use emacs, but any editor will do.

1
emacs -nw map.go

Copy the code below:

1
2
3
4
5
6
7
8
9
10
11
12
package main

import "fmt"

func main() {
elements := make(map[string]string)
elements["O"] = "Oxygen"
elements["Ca"] = "Calcium"
elements["C"] = "Carbon"

fmt.Println(elements["C"])

Run your go program:

1
go run map.go

Hashmap

The above creation of code works but it’s a bit over expressive.
You can define a map as a block of data, in which there is the same key value mapping.

1
2
3
4
5
alpha := map[string]int{
"A" : 1,
"B" : 2,
"C" : 3,
}

This will do the exactly the same, but is a more elegant notation.

Store information

You can use a map to store information.
We change the map, into a map of strings to maps of strings to strings.

1
website := map[string]map[string]string {

Then you can store information like this:

1
2
3
4
5
6
7
8
9
10
website := map[string]map[string]string {
"Google": map[string]string {
"name":"Google",
"type":"Search",
},
"YouTube": map[string]string {
"name":"YouTube",
"type":"video",
},
}

Then get a value using two keys,

1
2
fmt.Println(website["Google"]["name"])
fmt.Println(website["Google"]["type"])