Summary - Map
- Go course
- Beginner
- Lesson 56/90
- 4 min
Combine map concepts to write a dictionary.
Maps summary
Creating: map[K]V{...} or make(map[K]V) (a nil map can't be written). Reading: m[k] (zero value if missing), v, ok := m[k] (existence). Writing: m[k] = v, m[k]++. Deleting: delete(m, k), clear(m). Iterating: range (random order). Maps behave like references and aren't safe for concurrent writes.
Grouping
One of the most common uses of a map is grouping data by a property:
urunler := []struct{ Ad, Kategori string }{
{"Kalem", "kırtasiye"}, {"Elma", "meyve"}, {"Defter", "kırtasiye"},
}
grup := map[string][]string{}
for _, u := range urunler {
grup[u.Kategori] = append(grup[u.Kategori], u.Ad)
}
fmt.Println(grup["kırtasiye"]) // [Kalem Defter]Practice Group by category
Group the product list above by category with a map[string][]string. Print len(grup) and grup["kırtasiye"] on one line.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
urunler := []struct{ Ad, Kategori string }{
{"Kalem", "kırtasiye"}, {"Elma", "meyve"}, {"Defter", "kırtasiye"},
}
grup := map[string][]string{}
for _, u := range urunler {
grup[u.Kategori] = append(grup[u.Kategori], u.Ad)
}
fmt.Println(len(grup), grup["kırtasiye"])
}Expected output
2 [Kalem Defter]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which type fits storing several grades per student?
- map[[]int]string
- map[string]int
- []map[int]
- map[string][]int Correct answer
Explanation: The value can be a slice; m[ad] = append(m[ad], not) appends even to a nil slice. A slice can't be a key.
2 Add to the group
grup[k] = ____(grup[k], ad)
grup[k] = append(grup[k], ad)
Explanation: A missing key returns a nil slice, so append adds the first element without trouble.
3 Group summary
| Term | Meaning |
|---|---|
make(map[K]V) |
Creating |
v, ok := m[k] |
Existence check |
delete(m, k) |
Deleting |
map[K][]V |
Grouping |