Read Me First

Refer to the Go Language Specification documentation for map type. A copy of the map type specification posted on this website.

MapType     = "map" "[" KeyType "]" ElementType .
KeyType     = Type .
Type      = TypeName | TypeLit | "(" Type ")" 

Map build-in function


Syntax : keyword [ key type ] element type

Keyword : map

[key type] can be all Go type EXCEPT map, slice and function

s := make([]string,0)

Invalid key type map[s]string, s is a slice of string type.

Element type can be byte, int, float64, string, struct

var m map[int]int

m := map[int]int

m := map[int]string

m := map[string]int

m := map[string]string

Map of struct type

type name struct {
     firstName string
     lastName string
     age int

Note: the key type must NOT be function, map or slice

m := map[string]name

Initialize a map using the make function, value of nil assigned

myMap := make(map[int]string)

initialize the map with some values

myMap = map[int]string{1: “first”, 2: “Second”, 3: “third”}

Add elements into the map

m := map[string]float64{
    "pi" : 3.14,
    "ftom" : 0.3,

Map literal add two(2) element added to m. Note the operator “:=” and {} backets end of

m := map[string]string
m["first"] = "first name"

To obtain a value from a map

//x will hold the value in “myMap” that corresponds to key 3
var x = myMap[3]

Check if a key exists in a map

//If the key 5 is not in “myMap”, then “ok” will be false
//Otherwise, “ok” will be true, and “x” will be the value
x,ok := myMap[5]

Type      = TypeName | TypeLit | "(" Type ")"