Golang: Map

By Xah Lee. Date: . Last updated: .

What is Map

Map is a unordered collection of key value pairs. (similar to Python Dictionary or Ruby Hash Table or Java Map, JavaScript Map ).

Each key value pair is called a element.

Syntax of Map Type

Syntax of the map type.

map[keyType]valueType

package main

import "fmt"

func main() {

	// declare xx to be map type. key string, value int
	var xx map[string]int

	// print the type of xx
	fmt.Println(fmt.Sprintf("%T", xx) == "map[string]int")
}

Create Map, Literal Expression

map[keyType]valueType{ key1: value1, key2: value2, etc}

Create a map, with keys and values.

package main

import "fmt"

func main() {
	var xx = map[string]int{"a": 1, "b": 2}
	fmt.Println(xx) // map[a:1 b:2]
}

Create Map with make

make(map[keyType]valueType)

Create a empty map.

package main

import "fmt"

func main() {

	var xx = make(map[string]int)

	xx["a"] = 1
	xx["b"] = 2

	fmt.Println(xx) // map[a:1 b:2]
}

Length

use len to get number of items.

package main

import "fmt"

func main() {
	var xx = map[string]int{"a": 1, "b": 2}
	fmt.Printf("%v\n", len(xx))
    // 2
}

Check Key Exist

example

value, exists := myMap[key]

package main

import "fmt"

func main() {
	var xx = map[string]int{"a": 1, "b": 2}

	// check if key c exist
	if _, xexist := xx["c"]; xexist {
		fmt.Printf("yes")
	} else {
		fmt.Printf("no")
	}
	// no
}

Get Value

m[k]
  • Return 2 values.
  • First value is the value of key k in map m.
  • Second value is true if the key exist, else false.
  • You can get both values by var a, b = m[k]

When a key does not exist, the first value is map's value's type's Zero Value. (e.g. if the map's value's type is integer, it return 0 if the key doesn't exist.)

package main

import "fmt"

func main() {

	var mm = map[string]int{"a": 1, "b": 2}

	// get
	fmt.Println(mm["a"] == 1)

	// return 2 values. second is true if exist, else false
	var v1, v2 = mm["b"]
	fmt.Println(v1 == 2, v2 == true)
}

Set Value, Add Key

m[k] = v
  • Sets value v to key k in map m.
  • Create it if the key does not exist.
package main

import "fmt"

func main() {

	var xx = map[string]int{"a": 1, "b": 2}

	// set value to existing key
	xx["a"] = 9
	fmt.Println(xx["a"] == 9)

	// if key don't exist, add it
	xx["c"] = 8
	fmt.Println(xx["c"] == 8)

}

Delete Key

delete(m, k)
  • Delete the key k in m.
  • If key doesn't exist, do nothing.
package main

import "fmt"

func main() {

	var xx = map[string]int{"a": 1, "b": 2}

	// delete a key
	delete(xx, "a")
	fmt.Println(xx["a"] == 0)
	// non exist key return a value of zero value of the value type

	// if key doesn't exist, do nothing. no error out
	delete(xx, "999")

}

Loop Thru Map

Golang, data structure