go map code example

Example 1: create map golang

//map in go is a built in type implementaiton of has table
//create a empty map
myMap := make(map[string]string)
//insert key-value pair in map
myMap["key"] = "value"
//read from map
value, ok := myMap["key"]
//delete from map
delete(myMap, "key")

Example 2: go add to map

m := make(map[string]int)
m["numberOne"] = 1
m["numberTwo"] = 2

Example 3: golang map

package main

import (
	"fmt"
)

type User struct {
	Name string
	Age  int
}

func main() {

	var person = map[string]string{
		"name": "john doe",
		"age":  "23",
	}

	var profile = make(map[string]string)
	profile["name"] = "jane doe"
	profile["age"] = "23"

	var user = make(map[string]interface{})

	user["name"] = "peter parker"
	user["age"] = 30

	var users = []map[string]interface{}{
		{"name": "monkey d lufy", "age": 19},
		{"name": "trafagar d law", "age": 23},
		{"name": "nico robin", "age": 20},
	}

	var userStruct = map[string]User{
		"name": {Name: "Monkey D Lufy"},
		"age":  {Age: 19},
	}

	fmt.Println(person)
	fmt.Println(profile)
	fmt.Println(user)
	fmt.Println(users)
	fmt.Println(userStruct)
}

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
}

Example 5: go maps

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

Example 6: go maps

var m map[string]int
m = make(map[string]int)
m["key"] = 42
fmt.Println(m["key"])

delete(m, "key")

elem, ok := m["key"] // test if key "key" is present and retrieve it, if so

// map literal
var m = map[string]Vertex{
    "Bell Labs": {40.68433, -74.39967},
    "Google":    {37.42202, -122.08408},
}

// iterate over map content
for key, value := range m {
}

Tags:

Misc Example