The example in this article describes the go language map usage. Share to everyone for your reference. The specific analysis is as follows:
Map map key to value:
A map must be created with make (not new) before it can be used, and a map with a value of nil is empty and cannot be assigned a value.
Copy Code code 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,
}
Fmt. Println (m["Bell Labs"])
}
The grammar of the map is similar to that of the structural body grammar, but the key name is required.
Copy Code code 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 () {
Fmt. Println (M)
}
If the top-level type has only a type name, you can omit the key name in the element of the grammar.
Copy Code code 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 () {
Fmt. Println (M)
}
Modify Map:
Insert or modify an element in map m:
Copy Code code as follows:
Get elements:
Copy Code code as follows:
To delete an element:
Copy Code code as follows:
To detect a key existence through a double assignment:
Copy Code code as follows:
If the key is in M, OK is true. Otherwise, OK is false and Elem is the 0 value of the element type of the map.
Similarly, when a nonexistent key is read from a map, the result is a value of 0 for the element type of the map.
Copy Code code as follows:
Package Main
Import "FMT"
Func Main () {
M: = Make (Map[string]int)
m["Answer"] = 42
Fmt. Println ("The Value:", m["Answer"])
m["Answer"] = 48
Fmt. Println ("The Value:", m["Answer"])
Delete (M, "Answer")
Fmt. Println ("The Value:", m["Answer"])
V, OK: = m["Answer"]
Fmt. Println ("The Value:", V, "Present?", OK)
}
I hope this article will help you with your go language program.