Maps
Lesson 17 of 21 in Coddy's Slices and Maps in Golang course.
A map is a collection type, just like an array and a slice. It stores data in key-value pairs and allows fast lookup for the values.
The syntax for declaring a map is as follows:
products := map[string]int{}Similar to declaring variables for arrays and slices, we can use the short declaration (:=) or the var keyword followed by the name, followed by the keyword map, and inside the brackets, we specify the key type, and finally, we specify the value type or element type.
Slices and arrays are also key-value types, but the key is just the index. In maps, we can use any type as a key as long as it's comparable. Usually, the types are int and string.
All elements in the map should be of the same type; you cannot mix types in one map.
Let's initialize our map:
products := map[string]int{
"iPhone": 1200,
"MacBook": 4000,
"Keyboard": 400,
}Similar to slices and arrays, we can access the elements using keys. In this case, the key is what we've defined for each element. For example, to get the price of the keyboard:
fmt.Println("The Price of Keyboard:", products["Keyboard"])Output:
The Price of Keyboard: 400We can print all the elements of the map, just like a slice:
fmt.Println(products)And the result would be:
map[iPhone:1200 MacBook:4000 Keyboard:400]
Challenge
EasyWe have a set of books, each with a different number of pages, as follows:
- Python book has 300 pages
- Golang book has 400 pages
- Rust book has 500 pages
Implement this using a map and print the number of pages for the Golang book to the screen.
Try it yourself
package main
import "fmt"
func main() {
// Define a map
// Print the number of pages for the Golang book
}All lessons in Slices and Maps in Golang
1Introduction
Introduction