Challenge - 5 Problems
Go Map Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Go code when adding and updating map values?
Consider the following Go program that adds and updates values in a map. What will it print?
Go
package main import "fmt" func main() { scores := map[string]int{"Alice": 10, "Bob": 15} scores["Alice"] += 5 scores["Charlie"] = 20 fmt.Println(scores) }
Attempts:
2 left
💡 Hint
Remember that updating a map value with += adds to the existing value.
✗ Incorrect
The map starts with Alice:10 and Bob:15. Alice's score is increased by 5, making it 15. Charlie is added with 20. So the final map has Alice:15, Bob:15, and Charlie:20.
❓ Predict Output
intermediate2:00remaining
What happens when you update a map value for a non-existent key?
Look at this Go code snippet. What will be the output?
Go
package main import "fmt" func main() { ages := map[string]int{"John": 30} ages["Mary"] += 5 fmt.Println(ages) }
Attempts:
2 left
💡 Hint
When you add to a zero value in a map, Go initializes it to zero first.
✗ Incorrect
Mary is not in the map initially, so ages["Mary"] returns 0. Adding 5 sets Mary to 5. The map now has John:30 and Mary:5.
🔧 Debug
advanced2:00remaining
Why does this Go code cause a runtime panic when updating a map?
Examine the code below. It causes a runtime panic. What is the reason?
Go
package main func main() { var data map[string]int data["key"] = 1 }
Attempts:
2 left
💡 Hint
Maps must be initialized before you can add or update values.
✗ Incorrect
The variable 'data' is declared but not initialized, so it is nil. Assigning to a nil map causes a runtime panic.
❓ Predict Output
advanced2:00remaining
What is the output after updating nested map values?
Given this Go code with nested maps, what will be printed?
Go
package main import "fmt" func main() { users := map[string]map[string]int{ "user1": {"score": 10}, "user2": {"score": 20}, } users["user1"]["score"] += 5 users["user3"] = map[string]int{"score": 15} fmt.Println(users) }
Attempts:
2 left
💡 Hint
You can update nested map values by accessing keys step by step.
✗ Incorrect
user1's score is increased from 10 to 15. user3 is added with score 15. user2 remains unchanged.
🧠 Conceptual
expert2:00remaining
How many items are in the map after these operations?
Consider this Go code snippet. How many key-value pairs does the map contain at the end?
Go
package main import "fmt" func main() { m := make(map[int]string) for i := 0; i < 5; i++ { m[i] = fmt.Sprintf("val%d", i) } m[2] = "updated" delete(m, 4) fmt.Println(len(m)) }
Attempts:
2 left
💡 Hint
Remember that deleting a key reduces the map size by one.
✗ Incorrect
Initially 5 keys (0 to 4) are added. Key 2 is updated but not added anew. Key 4 is deleted, so 4 keys remain.