×

go · level 1 · unit 7 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

hands the answer back so you can keep it.

So far your functions print. Printing shows a value, and then it is gone: your program cannot keep it or do maths with it. To return a value instead, write return and the value.

Put the after the brackets: func double(n int) int promises to hand back an int. The call then turns into the answer, so double(4) becomes 8, ready to store or print.

A Go function can hand back two values at once. func share(sweets int, friends int) (int, int) returns how many each friend gets and how many are left. Catch both: each, left := share(7, 2).

package main
import "fmt"
func share(sweets int, friends int) (int, int) {
	return sweets / friends, sweets % friends
}
func main() {
	each, left := share(7, 2)
	fmt.Println("Each friend gets", each)
	fmt.Println("Left over:", left)
}

If you only need one of the two, catch the other with _, like each, _ := share(7, 2).