Go provides the Map data structure when 2 values need to be associated with each other. They are stored in a key-value format.
Map Format
Map is written as
map[key-Type] value-Type
Map Declaration
Let's see how we can declare a map,
First we can use a var declaration, to create a map variable that's set to its zero value:
var ex map[string] int
Here ex is declared to be a map with string keys and int values.
We can also use := declaration to create a map variable
ex2 := map[string] int{}
Reading and Writing in Map
example := map[string]int{}
example["A"] = 1
example["B"] = 3
example["C"] = 2
fmt.Println(example["D"])
example["D"]++
example["A"] = 2
fmt.Println(example["B"])
fmt.Println(example)
0
3
map[A:2 B:3 C:2 D:1]
Here we are assigning a value to a map key by using = . Also we can't use := to assign a value to a map key. We can read the value assigned to a key by putting the key within brackets.
++ operator is used to increment the value of the map key
Comma Ok Idiom
Comma Ok is used to find the existence of a key in a map. If a key exists in a map then value and bool(true or false) is returned.
If the key exists then the respective value and true is returned, else the value and false is returned.
m := map[string] int{
"john": 4,
"paul": 0,
}
a, b := m["john"]
fmt.Println(a, b)
c, d := m["paul"]
fmt.Println(c, d)
e, f := m["george"]
fmt.Println(e, f)
4 true
0 true
0 false
As we can see in the above example, john and paul are present in the map and we are getting the value and true as the output. Since george isn't present we get the 0 value and false as the output.
Deleting from Map
m1 := map[string]int{
"ab": 12,
"bc": 2,
}
fmt.Println(m1)
// Takes the map and key,and removes the key value pair
delete(m1, "ab")
fmt.Println(m1)
map[ab:12 bc:2]
map[bc:2]
delete function takes a map and key & removes the key-value pair as we can see in the above example. As we specified the "m1" map and "ab" key, the key-value pair is removed from the map.