Multiple Return Values
A Go function can return more than one value. Write the return types inside parentheses, and in the return line separate the values with commas:
package main
import "fmt"
func divide(a, b int) (int, int) {
return a / b, a % b
}
func main() {
q, r := divide(17, 5)
fmt.Println("Quotient:", q)
fmt.Println("Remainder:", r)
}
Output:
Quotient: 3
Remainder: 2
(int, int) says that divide gives back two int values. return a / b, a % b sends back the quotient first and the remainder second. On the calling side, q, r := makes two variables and fills them in the same order: q gets 3 and r gets 2.
You must take all the values. If you give only one variable, Go refuses to compile:
package main
import "fmt"
func divide(a, b int) (int, int) {
return a / b, a % b
}
func main() {
q := divide(17, 5)
fmt.Println(q)
}
Output:
# command-line-arguments
./main.go:10:7: assignment mismatch: 1 variable but divide returns 2 values
Skipping a value with _
Sometimes you need only one of the values. You cannot write q, r := and then leave q unused, because Go does not allow unused variables. Instead, write _, the blank identifier, in place of the value you do not want. Go throws that value away:
package main
import "fmt"
func divide(a, b int) (int, int) {
return a / b, a % b
}
func main() {
_, r := divide(17, 5)
fmt.Println("Remainder:", r)
}
Output:
Remainder: 2
A value and an ok flag
Go programs often return a result together with a bool that says if the result is real. Look at division by zero. There is no correct answer, but the function still has to return some int. So it returns 0 and false:
package main
import "fmt"
func safeDivide(a, b int) (int, bool) {
if b == 0 {
return 0, false
}
return a / b, true
}
func main() {
result, ok := safeDivide(10, 2)
fmt.Println(result, ok)
result, ok = safeDivide(10, 0)
if ok {
fmt.Println("Result:", result)
} else {
fmt.Println("Cannot divide by zero")
}
}
Output:
5 true
Cannot divide by zero
Why not just return 0 for a bad division? Because 0 can also be a real answer: safeDivide(0, 5) is 0. The bool removes the doubt. The caller checks ok before it uses the result. By habit, Go programmers name this variable ok.
The second call uses = and not :=, because result and ok already exist.
You will see this pattern again. The Maps lesson uses it to check if a key exists, and the Returning Errors lesson uses the same idea with an error value in place of the bool.
In the exercise, the function has a return inside a for loop. When that return runs, the whole function ends at once, so the loop stops too. Complete both return lines of smallestDivisor: the divisor and true when one is found, and 0 and false when n is prime.