You have been writing a function since Day 1: main. Today you write your own. A function gives a calculation a name. func double(minutes int) int takes one int parameter and returns an int. The caller supplies an argument, and return sends the result back. Keep the arithmetic in the function and print the result in main.
Naming a calculation pays off in three ways. The call site reads like a description of what happens, such as double(12), instead of the arithmetic itself. The same rule can be used in many places without being copied. And because a function takes inputs and returns an output, you can check it on its own, which you will do on Day 6.
Predict and run
What value comes back from double?
package main
import (
"fmt"
)
func double(minutes int) int {
return minutes * 2
}
func main() {
fmt.Println(double(12))
}Check your prediction
24Call double(0) and check the result.
Reading a function signature
The first line of a function is its signature, and it tells a caller everything needed to use it. In func double(minutes int) int:
funcstarts a function declaration.doubleis the name callers use.(minutes int)lists the parameters: a name, then its type. Inside the function,minutesis an ordinary variable holding whatever the caller passed.- The final
intis the result type. Every path through the function must end with areturnof that type, or the compiler reportsmissing return.
Functions are declared at the top level of the file, outside main. Their order in the file does not matter, so main can call a function written below it.
Several parameters
List parameters with commas. When neighbors share a type, you can write the type once after the last of them: done, goal int declares two int parameters. The caller must pass the same number of arguments, in the same order and of the same types.
package main
import (
"fmt"
)
func percent(done, goal int) int {
return done * 100 / goal
}
func main() {
fmt.Println(percent(45, 60), "%")
fmt.Println(percent(60, 60), "%")
}75 %
100 %Multiplying before dividing matters here. 45 / 60 * 100 would divide first, drop the remainder to get 0, and then multiply 0 by 100.
Arguments are copies
When you call a function, each parameter receives a copy of the argument's value. Changing a parameter inside the function changes only that copy; the caller's variable is untouched. To get a new value out of a function, return it and let the caller store it.
package main
import (
"fmt"
)
func addBonus(minutes int) int {
minutes += 10
return minutes
}
func main() {
minutes := 20
withBonus := addBonus(minutes)
fmt.Println(minutes, withBonus)
}20 30Calculate in the function, print in main
A function that returns a value can be used anywhere: in a Printf, in a condition or inside another calculation. A function that prints its answer can only print. Keep calculations returning values, and leave the printing to main. A function with no result type, such as func printHeader(), is fine when printing really is its whole job.
return ends the function
return does two things: it hands back the result, and it stops the function immediately. Any statements after it in the same path never run. You can use this to handle a special case early, for example returning 0 before dividing by a goal of 0, and then let the normal case follow without an else.
Practice
Your turn
Write a function named pagesLeft that takes the total number of pages in a book and the pages already read, both int, and returns how many pages are left. A reader who has read past the end, because the total was entered wrong, has 0 pages left, never a negative number. Call it from main for a 120-page book after 45 pages and after 130 pages. The output should be:
Left: 75
Left: 0package main
func main() {
// Write your code here.
}Hint 1: the idea
The function handles one special case and one normal case. When the pages read reach or pass the total, the answer is already known, and return can hand it back and stop there.
Hint 2: a first step
Write the signature func pagesLeft(total, read int) int above main and return total - read for now. The first line should be right and the second should print Left: -10. Then add the special case before that line.
Worked solution
package main
import (
"fmt"
)
func pagesLeft(total, read int) int {
if read >= total {
return 0
}
return total - read
}
func main() {
fmt.Println("Left:", pagesLeft(120, 45))
fmt.Println("Left:", pagesLeft(120, 130))
}Left: 75
Left: 0The early return 0 stops the function before the subtraction, so the normal case needs no else. Keeping the rule in a function means every part of the program that asks "how many pages are left?" gets the same answer, including the rule about never going below zero.
Completion is saved in this browser only. It does not measure mastery.