CodeBlanks Logo Icon CodeBlanks

Adding elements

Learn to add elements to a map by key.

Adding and updating elements

m[key] = value adds the key if it doesn't exist and updates its value if it does. Reading a missing key gives the value type's zero value; this is very handy for counters:

sayac := map[string]int{}
for _, k := range []string{"go", "sql", "go"} {
    sayac[k]++
}
fmt.Println(sayac)  // map[go:2 sql:1]

sayac[k]++ starts from 0 the first time, then increases.

Updating struct values

If a map value is a struct, its field can't be written directly: m["a"].Adet = 5 is a compile error. Read the value, change it, write it back:

u := stok["kalem"]
u.Adet += 2
stok["kalem"] = u

Alternatively the map holds pointers: map[string]*Urun; then stok["kalem"].Adet += 2 works.

Practice Word counter

Get the words with strings.Fields("go sql go web go") and count them with a map[string]int. Print the counts of go and web on one line.

Starter code

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "strings"
)

func main() {
    say := map[string]int{}
    for _, k := range strings.Fields("go sql go web go") {
        say[k]++
    }
    fmt.Println(say["go"], say["web"])
}

Expected output

3 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 For <code>m := map[string]int{}</code>, what does <code>m["yok"]</code> return?

  • nil
  • A panic
  • -1
  • 0 Correct answer

Explanation: For a missing key the int zero value is returned; to know whether the key really exists use the comma-ok form.

2 Increment the counter

Question
for _, kelime := range kelimeler {
    say[kelime]____
}
Answer
for _, kelime := range kelimeler {
    say[kelime]++
}

Explanation: say[kelime]++ starts a missing key at 0 and increments it.

3 Operation and result

Term Meaning
m["a"] = 1 (new) Adds
m["a"] = 2 (existing) Updates
m["yok"] Zero value
m["a"]++ Increments a counter

All lessons in Beginner