Maps in Golang

  • 14 April 2020
  • ADM

 

Maps in Golang - images/logos/golang.jpg

 

Golang maps implements a hash table. Hash tables are one of the most used data structure. A hash table is an unordered collection of key-value pairs, where each key is unique.

 

Golang maps declaration

The syntazx to declare a map is:

map[KeyType]ValueType

where KeyType can have any type that is comparable, like string, int, float, and ValueType can have any type.

Declaration and initialization

// a nil map of string-int pairs, this would still need to be initialized using make before usage
var map1 map[string]int

// Empty map of string-int pairs
map2 := make(map[string]int)

// map of string-int pairs with preallocate 10 elements
map3 := make(map[string]int, 10)

// Map literal of string-float64 pairs
map4 := map[string]float64{
	"price": 12.8,
	"units": 2.1,
}

Golang maps operations

Golang provides simple and intuitive ways how to work with maps. To add or to update an value is using the same syntax.

package main

import "fmt"

func main() {

	// Empty map of string-int pairs
	map2 := make(map[string]int)

	// this will print 0, the zero value of the value type, in this case int.
	fmt.Println(map2["key1"])

	//this will add a new entry in the map under key1
	map2["key1"] = 10
	// this will add print 10
	fmt.Println(map2["key1"])

	//this will update the value in the map under key1
	map2["key1"] = 33
	// this will add print 33
	fmt.Println(map2["key1"])
}

Output

0  
10 
33

To get the value you can use these examples:

v1 := map2["key1"] // Get value: v == 33
v2 = map2["key2"]  // Not found: v == 0 (zero value of the int type)

_, found := map2["key1"] // found == true
_, found = map2["key2"]  // found == false

//this will print the value 33
if val, found := map2["key1"]; found {
	fmt.Println(val)
}

 

Iterate over maps

To iterate over the contents of a map, you can use the range keyword:

package main

import "fmt"

func main() {

	days := map[string]string{
		"day1": "Monday",
		"day2": "Tuesday",
		"day3": "Wednesday",
		"day4": "Thursday",
		"day5": "Friday",
		"day6": "Saturday",
		"day7": "Sunday",
	}
	for key, val := range days {
		fmt.Println(key + ": " + val)
	}
}

Output

day1: Monday
day2: Tuesday
day3: Wednesday
day4: Thursday
day5: Friday
day6: Saturday
day7: Sunday

 

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build example.go

Assuming that example.go is the name of your file.

Then depending on if you are on Linux or Windows the binary file is created.

To run the application, execute the command.

Linux

$ ./example

Windows

c:\Users\adm\go\tutorials> example.exe

If you want to compile and run the application in one single step, run the following command:

go run example.go

 

References