Maps

Maps allow us to store values in a one-to-one way using key, value pairs.

Maps are a built-in associative data-structure in golang that allows us to store data in key-value pairs. Maps are synonymous to hashes or dicts in other languages. Below, we will go over some of the basics of maps in golang

Creating a new map

To create a new map, we use the make keyword

package main
import "fmt"

func main() {
  vending_machine := make(map[string]int)
  vending_machine["coke"] = 9
  vending_machine["beer"] = 3
  vending_machine["water"] = 24
  fmt.Println("number of items: ", len(vending_machine")
  fmt.Println("vending machine items", vending_machine)
  
  // we can also declare and init a map as follows
  inventory := map[string]int{"pepsi": 10, "sprite": 4, "rootbeer": 1}
  fmt.Println("inventory: ", inventory)
}

Get, update, delete, items in maps

We can add, delete, and change values of items in a map

package main
import "fmt"

func main() {
  vending_machine := make(map[string]int)
  vending_machine["coke"] = 9
  vending_machine["beer"] = 3
  vending_machine["water"] = 24
  fmt.Println("number of items: ", len(vending_machine")
  fmt.Println("vending machine items", vending_machine)
  
  coke_price := m["coke"]
  fmt.Println("number of coke bottles: ", coke_price)
  
  // the built-in method, delete removes the item from the map
  delete(vending_machine, "water")
  fmt.Println("vending machine ran out of water:", vending_machine)
  fmt.Println(len(vending_machine))
}

We can get the value of a map item using it's key. However, we may be interested in knowing if the key existed or not when getting the value. We do so by using the syntax

value, key_present = vending_machine["tea"]
// value: nil
// key_present: false

This method can be used to disambiguate between missing keys and keys with zero values like 0 or "".

Last updated