Maps in Go
Go has one associated data structure - “map”. Map is a hash table where you can store data in key/value pairs. Following syntax is used to create a map.
var x map[keyType]valType
Type of the key is defined within []
and type of value is defined followed by it.
For example:
package main
import "fmt"
func main() {
var x map[string]int
fmt.Println(x)
}
Output is:
map[]
Variable x
can hold key/value pair with key
as type of string
and value
as type of int
. The type of the key should be the type that is comparable such as int
, string
, or an array
. But, slice
is not allowed as slice
is not comparable. The above example create a null map. Adding key/value in null map panic and throw error.
For example:
package main
import "fmt"
func main() {
var x map[string]int
x["a"] = 1
fmt.Println(x)
}
Output is:
panic: assignment to entry in nil map
But, assigning value in empty map created using make()
function is allowed.
package main
import "fmt"
func main() {
x := make(map[string]int)
x["a"] = 1
fmt.Println(x)
}
Output is:
map[a:1]
Of course, you can create a map with the initial values if you have.
package main
import "fmt"
func main() {
x := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
fmt.Println(x)
}
Output is:
map[a:1 b:2 c:3]
We can access the value from the map using key, writing it within box bracket.
For example:
package main
import "fmt"
func main() {
x := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
fmt.Println(x["a"])
fmt.Println(x["b"])
fmt.Println(x["c"])
}
Output is:
1
2
3
If given key does not exist in map, it will return zero value of value.
For example:
package main
import "fmt"
func main() {
x := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
fmt.Println(x["z"])
}
Output is:
0
But, if you still want to check if the given key exists or not, then it optionally return second argument that is boolean and tell if given key is exists or not.
For example:
package main
import "fmt"
func main() {
x := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
v, exists := x["z"]
fmt.Println(v)
fmt.Println(exists)
}
Output is:
0
false
If you want to remove given key/value pair, delete()
function is used. The first argument should be the map and second argument should be the key which need to be deleted.
For example:
package main
import "fmt"
func main() {
x := map[string]int{
"a": 1,
"b": 2,
"c": 3,
}
delete(x, "a")
fmt.Println(x)
}
Output is:
map[b:2 c:3]
There are some other useful functions available in maps std library. But, this library is still in experimental phase.