0
0
Goprogramming~10 mins

Program stability concepts in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to recover from a panic and print a message.

Go
func safeDivide(a, b int) int {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println([1])
        }
    }()
    return a / b
}
Drag options to blanks, or click blank then click option'
A"Panic happened"
B"Error occurred"
C"Division successful"
D"Recovered from panic!"
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to check if recover() is nil before printing.
Not using defer to call the recovery function.
2fill in blank
medium

Complete the code to handle a panic and return zero instead of crashing.

Go
func safeAccess(arr []int, index int) int {
    defer func() {
        if r := recover(); r != nil {
            [1]
        }
    }()
    return arr[index]
}
Drag options to blanks, or click blank then click option'
Afmt.Println("Recovered from panic")
Breturn 0
Cpanic("index out of range")
Dfmt.Println("Access successful")
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to return a value inside defer without named return variables.
Not recovering from panic at all.
3fill in blank
hard

Fix the error in the code to properly recover from panic and set the return value.

Go
func safeDivide(a, b int) (result int) {
    defer func() {
        if r := recover(); r != nil {
            [1]
        }
    }()
    result = a / b
    return
}
Drag options to blanks, or click blank then click option'
Apanic("division error")
Breturn 0
Cresult = 0
Dfmt.Println("Recovered")
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use 'return' inside defer which is not allowed.
Not using named return variables to modify the return value.
4fill in blank
hard

Fill both blanks to create a map of string to int with only keys having length greater than 3.

Go
words := []string{"go", "code", "chat", "ai"}
lengths := map[string]int{
    [1]: len([2]) for _, word := range words if len(word) > 3
}
Drag options to blanks, or click blank then click option'
A"word"
Bword
C"words"
Dwords
Attempts:
3 left
💡 Hint
Common Mistakes
Using the slice name 'words' instead of the variable 'word'.
Not quoting the map key properly.
5fill in blank
hard

Fill all three blanks to create a map of uppercase keys to their lengths for words longer than 2 characters.

Go
words := []string{"go", "code", "chat", "ai"}
lengths := map[string]int{
    [1]: [2] for _, [3] := range words if len(word) > 2
}
Drag options to blanks, or click blank then click option'
Astrings.ToUpper(word)
Blen(word)
Cword
Dw
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'word' instead of the loop variable 'w'.
Not converting keys to uppercase.