0
0
Goprogramming~10 mins

Named return values 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 declare a function with named return values.

Go
func greet() (message string) {
    message = "Hello, Go!"
    return [1]
}
Drag options to blanks, or click blank then click option'
Amessage
Bgreet
Cstring
Dmsg
Attempts:
3 left
💡 Hint
Common Mistakes
Returning a variable not declared as a named return value.
Returning the function name instead of the variable.
2fill in blank
medium

Complete the code to use named return values and omit the return expression.

Go
func add(a, b int) (sum int) {
    sum = a + b
    [1]
}
Drag options to blanks, or click blank then click option'
Areturn sum
Breturn a + b
Creturn
Dreturn sum + 1
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the variable explicitly when a bare return is enough.
Returning an incorrect expression.
3fill in blank
hard

Fix the error in the function by completing the return statement correctly.

Go
func divide(a, b float64) (result float64, err error) {
    if b == 0 {
        err = fmt.Errorf("division by zero")
        [1]
    }
    result = a / b
    return
}
Drag options to blanks, or click blank then click option'
Areturn 0, err
Breturn result, nil
Creturn err, 0
Dreturn nil, err
Attempts:
3 left
💡 Hint
Common Mistakes
Returning error and result in wrong order.
Returning nil instead of zero for result.
4fill in blank
hard

Fill both blanks to complete the function with named return values and a bare return.

Go
func multiply(a, b int) (product int, err error) {
    if a < 0 || b < 0 {
        err = fmt.Errorf("negative input")
        [1]
    }
    product = a * b
    [2]
}
Drag options to blanks, or click blank then click option'
Areturn
Breturn product, err
Creturn 0, err
Dreturn err
Attempts:
3 left
💡 Hint
Common Mistakes
Using bare return in the error case without setting product to zero.
Returning only error without product.
5fill in blank
hard

Fill all three blanks to complete the function using named return values and proper error handling.

Go
func subtract(a, b int) (result int, err error) {
    if a < b {
        err = fmt.Errorf("a is less than b")
        [1]
    }
    result = a - b
    [2]
    [3]
}
Drag options to blanks, or click blank then click option'
Areturn 0, err
Breturn
Creturn result, err
Dreturn err
Attempts:
3 left
💡 Hint
Common Mistakes
Returning error only without result.
Not using bare return after assigning result.