A map is an unordered collection of key-value pairs, similar to the dictionary in Python.
Declare a map using syntax map[KeyType]ValueType{}
. For example
package main
import "fmt"
func main() {
// Declare an empty map
a := map[string]int{}
a["Steak"] = 450
fmt.Println(a)
// Declare a map with initial value
b := map[string]int{
"Bubble Milk Tea": 55,
"Ice Coffee": 45,
}
fmt.Println(b)
}
The value assigned to a key in a map can be retrieved using the syntax m[key].
If the key does not exists in the map, you’ll get the zero value of the map’s value type.
However, this way might be confused when the key exist but the vale is 0.
To check the key exist in a map or not, we should using syntax value, ok := m[key]
package main
import "fmt"
func main() {
m := map[string]int{
"Bread": 30,
}
fmt.Println("bread's price is", m["Bread"])
// If a key doesn't exist in the map, we get the zero value of the value type
fmt.Println("Salad's price is", m["Salad"])
// key is case sensitive
fmt.Println("Bread's price is", m["bteak"])
// Appropriate way to check key exist or not
price, priceExist := m["Salad"]
if priceExist {
fmt.Println("Salad's price is", price)
} else {
fmt.Println("This store does not sell Salad")
}
}
We can delete a key from a map using the built-in delete()
function
b := map[string]int{
"Bubble Milk Tea": 55,
"Ice Coffee": 45,
}
delete(b, "Ice Coffee")
delete(b, "Cake") // No run time error even key does not exist.
fmt.Println(b)
Similar to array and slice, we can use range to iterate a map
package main
import "fmt"
func main() {
b := map[string]int{
"Bubble Milk Tea": 55,
"Ice Coffee": 45,
}
printMap(b)
}
func printMap(p map[string]int) {
for key, value := range p {
fmt.Printf("The price of %s is %d\n", key, value)
}
}
Similar to slice, map is reference type.
package main
import "fmt"
func main() {
b := map[string]int{
"Bubble Milk Tea": 55,
"Ice Coffee": 45,
}
var c = b
delete(c, "Ice Coffee")
fmt.Println(b) // output is map[Bubble Milk Tea:55]
fmt.Println(c) // output is map[Bubble Milk Tea:55]
updatePrice(c, "Bubble Milk Tea", 60)
fmt.Println(b) // output is map[Bubble Milk Tea:60]
fmt.Println(c) // output is map[Bubble Milk Tea:60]
}
func updatePrice(p map[string]int, key string, newPrice int) {
p[key] = newPrice
}