0
0
Goprogramming~20 mins

Multiple return values in Go - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Multiple Return Values 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 code with multiple return values?

Look at this Go function that returns two values. What will be printed?

Go
package main
import "fmt"

func divide(a, b int) (int, int) {
    return a / b, a % b
}

func main() {
    q, r := divide(10, 3)
    fmt.Println(q, r)
}
AError: cannot use divide(10, 3) in multiple assignment
B3 0
C3 3
D3 1
Attempts:
2 left
💡 Hint

Remember that the first return value is the quotient and the second is the remainder.

Predict Output
intermediate
2:00remaining
What happens when you ignore one return value in Go?

What will this program print?

Go
package main
import "fmt"

func getValues() (int, string) {
    return 42, "hello"
}

func main() {
    val, _ := getValues()
    fmt.Println(val)
}
A42
Bhello
CCompilation error due to unused variable
D42 hello
Attempts:
2 left
💡 Hint

The underscore (_) is used to ignore a return value.

Predict Output
advanced
2:00remaining
What is the output of this Go function returning named values?

Check the named return values and what the function returns.

Go
package main
import "fmt"

func swap(x, y int) (a int, b int) {
    a = y
    b = x
    return
}

func main() {
    a, b := swap(5, 10)
    fmt.Println(a, b)
}
A5 10
B10 5
C0 0
DCompilation error: missing return values
Attempts:
2 left
💡 Hint

Named return values can be returned by just using return without arguments.

Predict Output
advanced
2:00remaining
What error does this Go code produce when returning multiple values?

What error will this code cause?

Go
package main

func foo() (int, int) {
    return 1
}

func main() {}
Asyntax error: unexpected newline
Bmissing return at end of function
Ccannot use 1 (type int) as type (int, int) in return statement
Dno error, compiles fine
Attempts:
2 left
💡 Hint

Check the number of values returned compared to the function signature.

🧠 Conceptual
expert
2:00remaining
How many values does this Go function return and what are their types?

Analyze this function signature and tell how many values it returns and their types.

Go
func process(data []int) (sum int, avg float64, err error) {
    // implementation omitted
    return
}
AThree values: int, float64, and error
BTwo values: int and float64
CThree values: int, int, and error
DOne value: a struct containing int, float64, and error
Attempts:
2 left
💡 Hint

Look at the named return values and their types carefully.