go · level 1 · unit 7 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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).
guess first
The answer is handed back. Does anyone catch it?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func double(n int) int {
return n * 2
}
func main() {
score := 5
double(score)
fmt.Println(score)
}
your turn
Your turn. Build a dog years machine.
In the first blank, type how many dog years each year counts as. People often say 7. In the second, type your dog's age, real or made up, as a whole number.
output
press run to see what happens
fix it
Two answers, one box. Can you fix it?
output
press run to see what happens
- Read the error. How many values does share hand back, and how many boxes catch them?
- share returns two values, so it needs two boxes. You only need the first one here.
- Change line 7 to each, _ := share(10, 3), then run.
nailed it
your functions can hand back answers. :D
- Printing shows a value.
returnhands it back to use. - The return type goes after the brackets.
- A function can return two values: catch both, or use
_.
new words in your collection
- return
- return type
This lesson isn’t saved. A free account remembers every lesson you finish.