Golang: Map

By Xah Lee. Date: . Last updated: .

Map is a unordered collection of key value pairs. Similar to dictionary, hashtable, associative array, in other languages.

Each key value pair is called an element.

Syntax of Map Type

Syntax of the map type is:

map[key_type_name]value_type_name

package main

import "fmt"

func main() {

	// syntax of map type
	var mm map[string]int

	fmt.Printf("%T\n", mm)          // map[string]int
}

Create Map, Literal Expression

To create a map, with keys and values, do like this:

map[key_type]value_type{ key1: val1, key2: val2 …}

example:

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

package main

import "fmt"

func main() {

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

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

Create Map with make

you can create a empty map with make.

make(map[key_type]value_type)

example:

make(map[string]int)

package main

import "fmt"

func main() {

    var mp = make(map[string]int)

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

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

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 mm = map[string]int{"a": 1, "b": 2}

    // set value to existing key
        mm["a"] = 9
    fmt.Println(mm) // map[a:9 b:2]

    // if key don't exist, add it
        mm["c"] = 8
    fmt.Println(mm) // map[a:9 b:2 c:8]

}

get value

m[k] → returns 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”. (example: if the map's value's type is integer, it return 0 if the key doesn't exist.)

[see Zero Value]

package main

import "fmt"

func main() {

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

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

    // returns 2 values. second is true if exist, else false
    var y, z = mm["b"]
    fmt.Println(y, z) // 2 true

    // returns 2 values. second is true if exist, else false
    var h1, h2 = mm["c"]
    fmt.Println(h1, h2) // 0 false

}

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 mm = map[string]int{"a": 1, "b": 2}

	// delete a key
	delete(mm, "a")
	fmt.Println(mm) // map[b:2]

	// if key doesn't exist, do nothing
	delete(mm, "9")
	fmt.Println(mm) // map[b:2]

}

Loop Thru Map

example:

for key, val := range map { fmt.Printf("%v, %v\n", kk, vv) }

If one of the variable you don't need, name it _, else compiler will complain. The _ is called “blank identifier”.

package main

import "fmt"

func main() {

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

    for kk, vv := range mm {
        fmt.Printf("%v, %v\n", kk, vv)
    }
    // prints
    // a, 1
    // b, 2

}

[see Golang: loop]

Reference

The Go Programming Language Specification - The Go Programming Language#Map_types

The Go Programming Language Specification - The Go Programming Language#Deletion_of_map_elements

If you have a question, put $5 at patreon and message me.

Golang

  1. Compile, Run
  2. Source Encoding
  3. Package, Import
  4. Comment
  5. Print
  6. String
  7. String Backslash Escape
  8. Rune
  9. Variable
  10. Zero Value
  11. Constant
  12. If Then Else
  13. Switch/Case
  14. Loop
  15. Basic Types
  16. Array
  17. Slice
  18. Map
  19. Struct
  20. Function
  21. Pointer
  22. String as Chars
  23. regexp
  24. Read File
  25. Write to File
  26. Walk Dir
  27. Check File Exist
  28. System Call
  29. Get Script Path
  30. Pointer
  31. Defer
  32. Random Number

Examples

  1. Match Any Regexp
  2. Find Replace
  3. Validate Links
  4. Generate Sitemap

Reference

  1. Go Spec