SoFunction
Updated on 2025-03-05

Example analysis of Go language map usage

This article describes the usage of Go map. Share it for your reference. The specific analysis is as follows:

map map key to value:

Map must be created with make (not new) before use; a map with a value of nil is empty and cannot be assigned.

Copy the codeThe code is as follows:
package main
import "fmt"
type Vertex struct {
    Lat, Long float64
}
var m map[string]Vertex
func main() {
    m = make(map[string]Vertex)
    m["Bell Labs"] = Vertex{
        40.68433, 74.39967,
    }
    (m["Bell Labs"])
}

 
The grammar of map is similar to the grammar of structure, but the key name is necessary.
Copy the codeThe code is as follows:
package main
import "fmt"
type Vertex struct {
    Lat, Long float64
}
var m = map[string]Vertex{
    "Bell Labs": Vertex{
        40.68433, -74.39967,
    },
    "Google": Vertex{
        37.42202, -122.08408,
    },
}
func main() {
    (m)
}

 
If the top-level type only has a type name, the key name can be omitted from the grammar elements.
Copy the codeThe code is as follows:
package main
import "fmt"
type Vertex struct {
    Lat, Long float64
}
var m = map[string]Vertex{
    "Bell Labs": {40.68433, -74.39967},
    "Google":    {37.42202, -122.08408},
}
func main() {
    (m)
}

 
Modify map:

Insert or modify an element in map m:

Copy the codeThe code is as follows:
m[key] = elem

Obtain elements:
Copy the codeThe code is as follows:
elem = m[key]

Delete elements:
Copy the codeThe code is as follows:
delete(m, key)

Detect the existence of a certain key through double assignment:
Copy the codeThe code is as follows:
elem, ok = m[key]

If key is in m, ok is true. Otherwise, ok is false and elem is the zero value of the element type of map.

Similarly, when reading a non-existent key from the map, the result is a zero value of the element type of map.

Copy the codeThe code is as follows:
package main
import "fmt"
func main() {
    m := make(map[string]int)
    m["Answer"] = 42
    ("The value:", m["Answer"])
    m["Answer"] = 48
    ("The value:", m["Answer"])
    delete(m, "Answer")
    ("The value:", m["Answer"])
    v, ok := m["Answer"]
    ("The value:", v, "Present?", ok)
}

I hope this article will be helpful to everyone's Go language programming.