A Golang map is a unordered collection of key-value pairs. For every key, there is a unique value. If you have a key, you can lookup the value in a map.
Sometimes its called an associative array or hash table. An example of a map in Go:
elements := make(map[string]string)Its defines as a string to string mapping. In this example we’ll use the periodic elements.
You can map on other variable types too. Below an example of string to int mapping:
alpha := make(map[string]int)
alpha["A"] = 1Map in golang
Map example
Create a new file named map.go, I like to use emacs, but any editor will do.
emacs -nw map.goCopy the code below:
package main
import "fmt"
func main() {
elements := make(map[string]string)
elements["O"] = "Oxygen"
elements["Ca"] = "Calcium"
elements["C"] = "Carbon"
fmt.Println(elements["C"])
Run your go program:
go run map.goHashmap
The above creation of code works but it’s a bit over expressive. You can define a map as a block of data, in which there is the same key value mapping.
alpha := map[string]int{
"A" : 1,
"B" : 2,
"C" : 3,
}This will do the exactly the same, but is a more elegant notation.
Store information
You can use a map to store information. We change the map, into a map of strings to maps of strings to strings.
website := map[string]map[string]string {Then you can store information like this:
website := map[string]map[string]string {
"Google": map[string]string {
"name":"Google",
"type":"Search",
},
"YouTube": map[string]string {
"name":"YouTube",
"type":"video",
},
}Then get a value using two keys,
fmt.Println(website["Google"]["name"])
fmt.Println(website["Google"]["type"])Exercises
- What is a map?
- Is a map ordered?
- What can you use a map for?