Challenge - 5 Problems
Map Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of iterating over a map with range
What is the output of this Go program?
Go
package main import "fmt" func main() { m := map[string]int{"a": 1, "b": 2, "c": 3} for k, v := range m { fmt.Printf("%s:%d ", k, v) } }
Attempts:
2 left
💡 Hint
Maps in Go do not guarantee order when iterating.
✗ Incorrect
In Go, iterating over a map with range produces keys in a random order each time. All key:value pairs are printed but order is not fixed.
❓ Predict Output
intermediate2:00remaining
Counting items in a map during iteration
What is the value of count after running this Go code?
Go
package main import "fmt" func main() { m := map[int]string{1: "one", 2: "two", 3: "three"} count := 0 for range m { count++ } fmt.Println(count) }
Attempts:
2 left
💡 Hint
Range over a map iterates over all keys.
✗ Incorrect
The loop runs once for each key in the map, so count increments 3 times.
❓ Predict Output
advanced2:00remaining
Modifying map values during iteration
What is the output of this Go program?
Go
package main import "fmt" func main() { m := map[string]int{"x": 1, "y": 2} for k := range m { m[k] = m[k] * 10 } fmt.Println(m) }
Attempts:
2 left
💡 Hint
You can modify map values during iteration safely in Go.
✗ Incorrect
Go allows modifying map values during iteration without error. The values are updated as expected.
❓ Predict Output
advanced2:00remaining
Iterating over a nil map
What happens when this Go code runs?
Go
package main import "fmt" func main() { var m map[string]int for k, v := range m { fmt.Println(k, v) } fmt.Println("Done") }
Attempts:
2 left
💡 Hint
Iterating over a nil map is safe and acts like empty map.
✗ Incorrect
In Go, iterating over a nil map does nothing and does not panic. The program prints "Done".
🧠 Conceptual
expert2:00remaining
Why is map iteration order random in Go?
Which reason best explains why Go's map iteration order is randomized?
Attempts:
2 left
💡 Hint
Think about why predictable order might be a problem.
✗ Incorrect
Go randomizes map iteration order to discourage code relying on order and to reduce certain security risks.