0
0
Goprogramming~20 mins

Accessing map values in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Map Mastery in Go
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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"])
}
Anil
B0
Cpanic: runtime error: invalid memory address or nil pointer dereference
DCompilation error
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.
Predict Output
intermediate
2: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)
}
A0 false
B0 true
CCompilation error
D10 false
Attempts:
2 left
💡 Hint
The second value returned when accessing a map key tells if the key exists.
🔧 Debug
advanced
2: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"])
}
AThe key "key" does not exist, so it returns zero value 0 without panic.
BThe code has a syntax error due to missing map initialization.
CThe map m is nil and not initialized, so accessing it causes a panic.
DThe program compiles but prints garbage value.
Attempts:
2 left
💡 Hint
Maps must be initialized before use to avoid runtime panic.
Predict Output
advanced
2: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"])
}
ACompilation error: cannot assign to map element
B1
C6
DRuntime panic
Attempts:
2 left
💡 Hint
You can update map values by accessing and assigning to the key.
Predict Output
expert
2: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])
}
AB
BEmpty string
CCompilation error: invalid map key type
DA
Attempts:
2 left
💡 Hint
Structs can be used as map keys if all their fields are comparable.