Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to access the value for key "name" in the map.
Go
person := map[string]string{"name": "Alice", "city": "Paris"}
value := person[[1]]
fmt.Println(value) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the key string.
Using a variable name without quotes.
✗ Incorrect
To access a value in a map by key, use the key as a string inside square brackets. Here, the key is "name".
2fill in blank
mediumComplete the code to check if the key "age" exists in the map.
Go
person := map[string]int{"age": 30, "score": 100}
value, [1] := person["age"]
if ok {
fmt.Println("Age is", value)
} else {
fmt.Println("Age not found")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name not matching the if condition.
Not using the second value to check existence.
✗ Incorrect
In Go, the second value when accessing a map is usually assigned to a variable named 'ok' by convention to check if the key exists.
3fill in blank
hardFix the error in accessing the map value safely.
Go
scores := map[string]int{"math": 90, "english": 85}
score, [1] := scores["science"]
if ok {
fmt.Println("Science score:", score)
} else {
fmt.Println("Science score not found")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name different from the one in the if condition.
Not assigning the second value from the map access.
✗ Incorrect
The idiomatic variable name to check if a key exists in a map is 'ok'.
4fill in blank
hardFill both blanks to create a map of string to int and access the value for key "apples".
Go
inventory := map[string]int[1]: 5, "oranges": 10} count := inventory[[2]] fmt.Println(count)
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different keys for map creation and access.
Forgetting quotes around the key strings.
✗ Incorrect
The map key "apples" must be used both when creating the map and when accessing its value.
5fill in blank
hardFill all three blanks to safely access a map value and print a message if the key "color" exists.
Go
attributes := map[string]string{"color": "blue", "size": "medium"}
value, [1] := attributes[[2]]
if [3] {
fmt.Println("Color is", value)
} else {
fmt.Println("Color not found")
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for the existence check.
Not using quotes around the key string.
Using a variable in the if condition that was not assigned.
✗ Incorrect
Use 'ok' to check if the key exists, the key string "color" to access the map, and the same 'ok' variable in the if condition.