Maps allow us to build a map of keys to values. For example, we can map a list of users to phone numbers to quickly retrieve the information. In this article, we will learn how to use Maps in Go.
To create maps, we need to use the make function. Here is an example.
phoneMap := make(map[string]string)Now that we have a map, we can add entries using the following syntax.
phoneMap["Jen"] = "555-5555"
phoneMap["Jane"] = "666-6666"To retrieve an entry in the list, we can just use the key as the index.
fmt.Println(phoneMap["Jane"]) // "666-6666"We can also loop over all the keys and values using the for and range keywords.
for person := range phoneMap {
fmt.Println("Person: ", person, " Phone: ", phoneMap[person])
}Finally, if we would like to remove a key, we need to use the delete function.
delete(phoneMap, "Jane")Here is a full example. You can use this by copying the contents to a file called main.go and running go run main.go.
package main
import "fmt"
func main() {
phoneMap := make(map[string]string)
phoneMap["Jen"] = "555-5555"
phoneMap["Jane"] = "666-6666"
fmt.Println(phoneMap["Jane"]) // "666-6666"
for person := range phoneMap {
fmt.Println("Person: ", person, " Phone: ", phoneMap[person])
}
delete(phoneMap, "Jane")
}