Go Maps
A "map" is a data type that is like a hash table with two columns: key and a value. It is similar to a Python dictionary. Keys of a map can be string or numbers. The value can be any data type. All values must have the same type.
Maps Basics
This is how a "map" declaration look like:
var x map[T] type
Where T is a type of the key and type is the type of the values.
Example:
//file map_type.go
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"])
}
Notes:
- A nil map has no keys, nor can keys be added to a nil map. This is the zero value of a map.
- The make function can be used to create a map of the given type, initialized and ready for use.
Map Declaration and Initialization
A map literal is a notation that describe all members of a maps that can be used to initialize a map variable. This literal notation is using nested braces { } to define the collection elements. Map literals are like struct literals and the keys are required.
//file map_literal.go
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)
}
Alternative
You can omit the type from the elements of the literal. This is alternative simplified sintax:
//map_alternative.go
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)
}
Mutating Maps
In next example we demonstrate several operations using a map "m".
//file map_mutation.go
package main
import "fmt"
func main() {
// declare a map m using type inference operator ":="
m := make(map[string]int)
// create a new element in the map
m["Answer"] = 42
fmt.Println("The value:", m["Answer"])
// create a new element in the map
m["Answer"] = 48
fmt.Println("The value:", m["Answer"])
// remove element from the map
delete(m, "Answer")
fmt.Println("The value:", m["Answer"])
// search for map element by name
v, ok := m["Answer"]
fmt.Println("v = ", v)
// expected: false
fmt.Println("The Answer is present?", ok)
}
Deleting Elements
The delete() function removes an element from a map.
Iterating Over Maps
You can use a for loop with range to iterate over map key-value pairs. The ok variable indicates whether the key was found in the map.
Output:
The value: 42
The value: 48
The value: 0
The Answer is present? false