0
0
Goprogramming~20 mins

Map creation in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Map Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this Go map creation code?
Consider the following Go code snippet that creates and initializes a map. What will be printed when this program runs?
Go
package main
import "fmt"
func main() {
    m := map[string]int{"apple": 5, "banana": 3}
    fmt.Println(m["apple"] + m["banana"])
}
ACompilation error
B8
C0
D53
Attempts:
2 left
💡 Hint
Remember that map values can be accessed by their keys and you can add integers.
Predict Output
intermediate
2:00remaining
What is the length of the map after this code runs?
Look at this Go code that creates a map and adds elements. What is the length of the map after execution?
Go
package main
import "fmt"
func main() {
    m := make(map[int]string)
    m[1] = "one"
    m[2] = "two"
    m[1] = "uno"
    fmt.Println(len(m))
}
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
Maps cannot have duplicate keys; adding a key again updates the value.
Predict Output
advanced
2:00remaining
What error does this Go code produce?
This Go code tries to create a map with a nil key. What error will it produce when compiled or run?
Go
package main
func main() {
    m := make(map[*int]string)
    var p *int = nil
    m[p] = "nil pointer"
}
Apanic: runtime error: hash of nil pointer
BCompilation error: invalid map key type
Cpanic: assignment to entry in nil map
DNo error, map accepts nil pointer as key
Attempts:
2 left
💡 Hint
In Go, nil pointers can be used as map keys if the key type is a pointer.
Predict Output
advanced
2:00remaining
What is the output of this Go map creation with composite literals?
What will this Go program print when run?
Go
package main
import "fmt"
func main() {
    m := map[string][]int{
        "a": {1, 2},
        "b": {3, 4},
    }
    m["a"] = append(m["a"], 5)
    fmt.Println(m["a"])
}
A[1 2 5]
B[1 2]
C[5]
DCompilation error: cannot use composite literal
Attempts:
2 left
💡 Hint
Appending to a slice inside a map updates the slice stored at that key.
🧠 Conceptual
expert
3:00remaining
Which option correctly creates a map with keys of type struct and values of type int?
You want to create a Go map where keys are structs with two int fields and values are integers. Which option correctly declares and initializes this map with one entry where the struct has fields 1 and 2, and the value is 10?
Am := map[struct{x, y int}]int{{1, 2}: 10}
Bm := map[struct{x int; y int}]int{struct{x int; y int}{1, 2}: 10}
Cm := map[struct{x int; y int}]int{{x: 1, y: 2}: 10}
D}01 :}2 :y ,1 :x{{tni]}tni y ;tni x{tcurts[pam =: m
Attempts:
2 left
💡 Hint
Struct field declarations in Go use semicolons or newlines, not commas, and composite literals can use field names.