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:
:= make(map[string]string) elements
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:
:= make(map[string]int)
alpha ["A"] = 1 alpha
Map in golang
Map example
Create a new file named map.go, I like to use emacs, but any editor will do.
-nw map.go emacs
Copy the code below:
package main
import "fmt"
func main() {
:= make(map[string]string)
elements ["O"] = "Oxygen"
elements["Ca"] = "Calcium"
elements["C"] = "Carbon"
elements
.Println(elements["C"])
fmt
Run your go program:
go run map.go
Hashmap
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.
:= map[string]int{
alpha "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.
:= map[string]map[string]string { website
Then you can store information like this:
:= map[string]map[string]string {
website "Google": map[string]string {
"name":"Google",
"type":"Search",
},
"YouTube": map[string]string {
"name":"YouTube",
"type":"video",
},
}
Then get a value using two keys,
.Println(website["Google"]["name"])
fmt.Println(website["Google"]["type"]) fmt
Exercises
- What is a map?
- Is a map ordered?
- What can you use a map for?