Challenge - 5 Problems
Map Mastery in Go
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of accessing a missing key in a map?
Consider the following Go code. What will be printed when accessing a key that does not exist in the map?
Go
package main import "fmt" func main() { m := map[string]int{"apple": 5, "banana": 3} fmt.Println(m["orange"]) }
Attempts:
2 left
💡 Hint
In Go, accessing a map with a key that does not exist returns the zero value of the map's value type.
✗ Incorrect
When you access a map with a key that is not present, Go returns the zero value for the value type. Since the map stores ints, the zero value is 0.
❓ Predict Output
intermediate2:00remaining
How to check if a key exists in a map?
What will be the output of this Go program that checks if a key exists in a map?
Go
package main import "fmt" func main() { m := map[string]int{"x": 10} val, ok := m["y"] fmt.Println(val, ok) }
Attempts:
2 left
💡 Hint
The second value returned when accessing a map key tells if the key exists.
✗ Incorrect
Since "y" is not a key in the map, val is zero value 0 and ok is false.
🔧 Debug
advanced2:00remaining
Why does this code panic when accessing a map?
This Go code panics at runtime. What is the cause?
Go
package main import "fmt" func main() { var m map[string]int fmt.Println(m["key"]) }
Attempts:
2 left
💡 Hint
Maps must be initialized before use to avoid runtime panic.
✗ Incorrect
A nil map does not cause a runtime panic when accessed for reading. Accessing a nil map returns the zero value for the value type. However, writing to a nil map causes a panic.
❓ Predict Output
advanced2:00remaining
What is the output when modifying a map value?
What will this Go program print?
Go
package main import "fmt" func main() { m := map[string]int{"a": 1} m["a"] += 5 fmt.Println(m["a"]) }
Attempts:
2 left
💡 Hint
You can update map values by accessing and assigning to the key.
✗ Incorrect
The value for key "a" is incremented by 5, so 1 + 5 = 6 is printed.
❓ Predict Output
expert2:00remaining
What is the output of this map access with struct keys?
Given this Go code, what will be printed?
Go
package main import "fmt" type Point struct { X, Y int } func main() { m := map[Point]string{ {X: 1, Y: 2}: "A", {X: 3, Y: 4}: "B", } p := Point{X: 1, Y: 2} fmt.Println(m[p]) }
Attempts:
2 left
💡 Hint
Structs can be used as map keys if all their fields are comparable.
✗ Incorrect
The map has a key Point{1,2} with value "A", so printing m[p] outputs "A".