golang map get value code example

Example 1: initialize map in golang

// By default maps in Go behaves like a default dictionary in python
m := make(map[string]int)

m["Dio"] = 3
m["Jonathan"] = 1

Example 2: go remove from map

m := map[string]string{"key1": "val1", "key2": "val2"}
delete(m, "key1")

Example 3: dictionary golang

package main

import (
    "fmt"
)

func main() {
    dict := map[interface{}]interface{} {
        1: "hello",
        "hey": 2,
    }
    fmt.Println(dict) // map[1:hello hey:2]
}

Example 4: go get from map

var id string
var ok bool
if x, found := res["strID"]; found {
     if id, ok = x.(string); !ok {
        //do whatever you want to handle errors - this means this wasn't a string
     }
} else {
   //handle error - the map didn't contain this key
}

Tags:

Java Example