Golang: 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
map[key_type]value_type
-
Syntax of the map type. Example:
var x map[string]int
declare a map, with key of string and value of int.
package main import "fmt" func main() { // declare mm to be map type var mm map[string]int fmt.Printf("%T\n", mm) // map[string]int }
Create Map, Literal Expression
map[key_type]value_type{ key1: val1, key2: val2 …}
-
Create a map, with keys and values. 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
make(map[key_type]value_type)
-
Create a empty map. 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] }
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, elsefalse
. You can get both values byvar a, b = m[k]
When a key does not exist, the first value is map's value's type's Golang: Zero Value. (example: 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 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 }
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] }
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
for key, val := range map { body }
-
Iterate thru map, each time with key key and value val in body.
If you don't need key or val, 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 }
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