Go Map
Last Updated: March 20, 2022
Map data structure in Go language stores data in key and value pairs.
Keys are unique identifiers
Adding and removing elements of Map are very easy.
Go Map Syntax
map[keyType] valueType
Creating Map in Golang
Initializing map with map literal
Zipcodes in map data structure
package main
import "fmt"
func main() {
zipcodes := map[string]int{
"Raleigh": 27615,
"Asheville": 28806,
"Concord": 28027,
"Greensboro": 27406,
}
fmt.Println(zipcodes)
}
Output
map[Asheville:28806 Concord:28027 Greensboro:27406 Raleigh:27615]
Another way to create map
var heights map[string]int
heights = make(map[string]int)
heights["Peter"] = 170
heights["John"] = 165
heights["Mike"] = 172
fmt.Println(heights) // map[John:165 Mike:172 Peter:170]
Check the existence of the element in map in Go
To check the given key exists in the map
if v, ok := heights["Jim"]; ok {
fmt.Println(v)
} else {
fmt.Println("Key does not exist")
}
Add an element to map in Golang
Remove element from the map in Golang
To delete an element in a map you can use the delete
method
if _, ok := heights["Mike"]; ok {
delete(heights, "Mike")
} else {
fmt.Println("Key does not exist")
}
Getting the number of elements in a map
To get the number of elements of the map in Goland you can use the len()
function
fmt.Println(len(heights))
How to iterate over map in Golang
To iterate over the map in Go you can use a for-range
loop
for k, v := range heights {
fmt.Println(k, v)
}