Maps
Maps allow us to store values in a one-to-one way using key, value pairs.
Last updated
Maps allow us to store values in a one-to-one way using key, value pairs.
Last updated
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
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)
}
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))
}