find the value associated with a key in a map in go

To find the value associated with a key in a Go map, we can simply use the following syntax:

main.go
value := yourMap[key]
22 chars
2 lines

Here, yourMap is the map we want to look up and key is the key for which we want to find the associated value. If the key is present in the map, its corresponding value will be returned in value. Otherwise, the zero value of the map's value type will be returned.

Here's an example that demonstrates how to find a value associated with a key in a Go map:

main.go
package main

import (
    "fmt"
)

func main() {
    // create a map of string keys and int values
    myMap := map[string]int{
        "foo": 2,
        "bar": 4,
        "baz": 6,
    }

    // look up the value associated with the key "bar"
    value := myMap["bar"]

    fmt.Println(value) // output: 4
}
310 chars
20 lines

In this example, we create a map myMap with string keys and integer values. We then look up the value associated with the key "bar" by using the indexing syntax with the square brackets. The value 4 is returned and printed to the console.

related categories

gistlibby LogSnag