Map
package main
import (
"fmt"
"maps"
)func main() {
// Create an empty map with string keys and int values
m := make(map[string]int)
// Assign values to keys in the map
m["k1"] = 7
m["k2"] = 13
// Print the entire map
fmt.Println("map:", m)
// Retrieve and print the value associated with the key "k1"
v1 := m["k1"]
fmt.Println("v1:", v1)
// Try to retrieve a value for a non-existent key "k3"
v3 := m["k3"]
fmt.Println("v3:", v3)
// Print the length of the map
fmt.Println("len:", len(m))
// Delete the key "k2" from the map
delete(m, "k2")
fmt.Println("map:", m)
// Clear the entire map
clear(m)
fmt.Println("map:", m)
// Check if the key "k2" exists in the map using a blank identifier (_)
_, prs := m["k2"]
fmt.Println("prs:", prs)
// Create and print a new map using a shorthand syntax
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println("map:", n)
// Create another map with the same content as "n" and check if they are equal
n2 := map[string]int{"foo": 1, "bar": 2}
if maps.Equal(n, n2) {
fmt.Println("n == n2")
}
}Output
Last updated