Looking up in a map
- Go course
- Beginner
- Lesson 53/90
- 4 min
Learn to get a value by key and check existence.
Map lookup: comma-ok
To know whether a key really exists, use the two-value read:
fiyat := map[string]float64{"kalem": 12.5, "hediye": 0}
if f, ok := fiyat["hediye"]; ok {
fmt.Println("var:", f) // var: 0
}
if _, ok := fiyat["silgi"]; !ok {
fmt.Println("silgi yok")
}Reading only fiyat["hediye"], you couldn't tell whether 0 means "free" or "missing".
A map as a set
Go has no separate set type; map[T]bool or the more memory-friendly map[T]struct{} is used:
gorulen := map[string]bool{}
for _, ad := range []string{"ada", "can", "ada"} {
if gorulen[ad] {
fmt.Println("tekrar:", ad)
continue
}
gorulen[ad] = true
}With map[T]bool, a missing key returns false, so comma-ok isn't needed.
Practice Price query
Write fiyatSor(m map[string]float64, ad string) string: if the product exists return fmt.Sprintf("%s: %.2f", ad, f), otherwise ad + " bulunamadı". Print the results for "kalem" and "silgi".
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func fiyatSor(m map[string]float64, ad string) string {
if f, ok := m[ad]; ok {
return fmt.Sprintf("%s: %.2f", ad, f)
}
return ad + " bulunamadı"
}
func main() {
m := map[string]float64{"kalem": 12.5}
fmt.Println(fiyatSor(m, "kalem"))
fmt.Println(fiyatSor(m, "silgi"))
}Expected output
kalem: 12.50 silgi bulunamadı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In <code>v, ok := m[k]</code>, what is returned if the key is missing?
- A panic
- The last value and true
- The zero value and false Correct answer
- nil and an error
Explanation: ok is true only if the key exists; v is the value type's zero value when it doesn't.
2 Existence check
if _, ____ := stok["kalem"]; !ok {
fmt.Println("stokta yok")
}
if _, ok := stok["kalem"]; !ok {
fmt.Println("stokta yok")
}
Explanation: The second value is a bool reporting whether the key is in the map.
3 Read and result
| Term | Meaning |
|---|---|
m["var"] |
The value |
m["yok"] |
The zero value |
_, ok := m["yok"] |
ok = false |
map[string]bool |
A set |