Getting started with Golang - 5-mapping

1. mapping

Map maps keys to values.

The zero value of the map is nil. Nil maps have no keys or add keys.

The make function returns a map of the given type and initializes it for standby.

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"])
}

output

{40.68433 -74.39967}

The grammar of the mapping is similar to the structure, but must have a key name.

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)
}

output

map[Bell Labs:{40.68433 -74.39967} Google:{37.42202 -122.08408}]

If the top-level type is just a type name, you can omit it from the grammar element.

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)
}

output

map[Google:{37.42202 -122.08408} Bell Labs:{40.68433 -74.39967}]

2. Modify mapping

Insert or modify elements in map m:

m[key] = elem

Get element:

elem = m[key]

Delete element:

delete(m, key)

Check whether a key exists by double assignment:

elem, ok = m[key]

If the key is in m, ok is true; otherwise, ok is false.

If the key is not in the mapping, then elem is the zero value of the mapping element type.

Similarly, when a nonexistent key is read from the map, the result is a zero value for the mapped element type.

Note: if elem or ok has not been declared, you can use short variable declaration:

elem, ok := m[key]

Give an example

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)
}

output

The value: 42
The value: 48
The value: 0
The value: 0 Present? false

Tags: Google

Posted on Sun, 05 Apr 2020 20:34:24 -0700 by chimp1950