bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Go/Go Tutorial
Go•Go Tutorial

Go Maps

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Go Maps?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

a = ___[KeyType]ValueType{
3Order

Put the learning moves in the order that makes the concept easiest to apply.

Allowed Value Types
Create an Empty Map
Create Maps Using var and :=

Maps are used to store data values in key:value pairs.

Each element in a map is a key:value pair.

A map is an unordered and changeable collection that does not allow duplicates.

The length of a map is the number of its elements. You can find it using the len() function.

The default value of a map is nil.

Maps hold references to an underlying hash table.

Go has multiple ways for creating maps.

Create Maps Using var and :=

Syntax

var
a = map[KeyType]ValueType{
 key1
 : value1 , key2
 : value2 ,...}
 b
 := map[KeyType]ValueType{
 key1
 : value1 , key2
 : value2 ,...}

Example

package main
import ("fmt")
func main() {
  var a = map[string]string{"brand": "Ford", "model": "Mustang", "year": "1964"}
  b := map[string]int{"Oslo": 1, "Bergen": 2, "Trondheim": 3, "Stavanger": 4}
  fmt.Printf("a\t%v\n", a)
  fmt.Printf("b\t%v\n", b)
}

Note

The order of the map elements defined in the code is different from the way that they are stored. The data are stored in a way to have efficient data retrieval from the map.

Syntax

var
a = make(map[KeyType]ValueType)
b
:= make(map[KeyType]ValueType)
make()

Create an Empty Map

There are two ways to create an empty map. One is by using the make() function and the other is by using the following syntax.

Syntax

var
a
map[KeyType]ValueType

Note

The make() function is the right way to create an empty map. If you make an empty map in a different way and write to it, it will causes a runtime panic.

make()

Allowed Key Types

The map key can be of any data type for which the equality operator ( == ) is defined. These include:

  • Booleans
  • Numbers
  • Strings
  • Arrays
  • Pointers
  • Structs
  • Interfaces (as long as the dynamic type supports equality)

Invalid key types are

  • Slices
  • Maps
  • Functions

These types are invalid because the equality operator ( == ) is not defined for them.

Allowed Value Types

The map values can be any type.

Access Map Elements

Syntax

value = map_name

Example

package main
import ("fmt")
func main() {
  var a = make(map[string]string)
  a["brand"] = "Ford"
  a["model"] = "Mustang"
  a["year"] = "1964"
  fmt.Printf(a["brand"])
}

Update and Add Map Elements

Updating or adding an elements are done by:

Syntax

map_name

Example

package main
import ("fmt")
func main() {
  var a = make(map[string]string)
  a["brand"] = "Ford"
  a["model"] = "Mustang"
  a["year"] = "1964"
  fmt.Println(a)
  a["year"] = "1970"
  // Updating an element a["color"] = "red" // Adding an element fmt.Println(a)
}

Remove Element from Map

Removing elements is done using the delete() function.

Syntax

delete( map_name , key)

Example

package main
import ("fmt")
func main() {
  var a = make(map[string]string)
  a["brand"] = "Ford"
  a["model"] = "Mustang"
  a["year"] = "1964"
  fmt.Println(a)
  delete(a,"year")
  fmt.Println(a)
}

Check For Specific Elements in a Map

You can check if a certain key exists in a map using:

Syntax

val , ok
:= map_name

If you only want to check the existence of a certain key, you can use the blank identifier ( _ ) in place of val.

Example

package main
import ("fmt")
func main() {
  var a = map[string]string{"brand": "Ford", "model": "Mustang", "year": "1964", "day":""}
  val1, ok1 := a["brand"]
  // Checking for existing key and its value val2, ok2 := a["color"] // Checking for non-existing key and its value val3, ok3 := a["day"] // Checking for existing key and its value _, ok4 := a["model"] // Only checking for existing key and not its value fmt.Println(val1, ok1) fmt.Println(val2, ok2) fmt.Println(val3, ok3) fmt.Println(ok4)
}

In this example, we checked for existence of different keys in the map.

The key " color " does not exist in the map. So the value is an empty string ('').

The ok2 variable is used to find out if the key exist or not. Because we would have got the same value if the value of the "color" key was empty. This is the case for val3 .

Iterate Over Maps

You can use range to iterate over maps.

Example

package main
import ("fmt")
func main() {
  a := map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}
  for k, v := range a {
    fmt.Printf("%v : %v, ", k, v)
  }
}

Iterate Over Maps in a Specific Order

Maps are unordered data structures. If you need to iterate over a map in a specific order, you must have a separate data structure that specifies that order.

Example

package main
import ("fmt")
func main() {
  a := map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}
  var b []string
  // defining the order b = append(b, "one", "two", "three", "four")
  for k, v := range a {
    // loop with no order fmt.Printf("%v : %v, ", k, v)
  }
fmt.Println()
for _, element := range b {
  // loop with the defined order fmt.Printf("%v : %v, ", element, a[element])
}
}

Previous

Go Struct

Next chapter

Practice

Start with Go Practice: Trace State