Deleting from a map
- Go course
- Beginner
- Lesson 54/90
- 4 min
Learn to delete elements from a map with the delete function.
Deleting from a map
The built-in delete(m, key) function removes the key from the map. If the key doesn't exist nothing happens; it doesn't error either:
stok := map[string]int{"kalem": 3, "silgi": 0}
delete(stok, "silgi")
delete(stok, "yok") // no problem
fmt.Println(len(stok)) // 1To remove all keys, clear(m) is available since Go 1.21.
Cleaning by condition
Cleaning out products that are out of stock in a single loop:
for ad, adet := range stok {
if adet == 0 {
delete(stok, ad)
}
}maps.DeleteFunc(stok, func(k string, v int) bool { return v == 0 }), added in Go 1.21, does the same in one line.
Practice Stock cleanup
Declare stok := map[string]int{"kalem": 3, "silgi": 0, "defter": 5, "cetvel": 0}. Delete the ones with quantity 0 using range + delete and print the number of remaining keys.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
stok := map[string]int{"kalem": 3, "silgi": 0, "defter": 5, "cetvel": 0}
for ad, adet := range stok {
if adet == 0 {
delete(stok, ad)
}
}
fmt.Println(len(stok))
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Is it safe to delete elements while iterating over a map with <code>range</code>?
- It doesn't compile
- Yes; Go explicitly supports it Correct answer
- No, it panics
- Only on the last element
Explanation: Keys deleted during iteration that haven't been seen yet won't come up; deleting is safe.
2 Delete the key
____(sepet, "kalem")
delete(sepet, "kalem")
Explanation: delete(m, k) removes key k from the map.
3 Operation and result
| Term | Meaning |
|---|---|
delete(m, "var") |
The key is removed |
delete(m, "yok") |
Nothing happens |
clear(m) |
All keys are removed |
maps.DeleteFunc |
Deletes by condition |