Lesson 1 · Unit 03
Defining functions
Parameters, results, return against print, several results, and scope.
What you practise
- Typed parameters and results,
returnagainst printing, several results at once, one function calling another, scope
Try a question from this lesson
Pick one
The first three lines describe a recipe called double: give it a number, and it hands back twice that number. What does this print?
func double(n int) int {
return n * 2
}
fmt.Println(double(4))
fmt.Println(double(10))Correct answer
8, then 20
Why
Each call runs the lines of double with n set to the number in the brackets. double(4) hands back 8, and double(10) hands back 20. One recipe, used twice.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Functions
A function is a named piece of work. func double(n int) int reads: the name is double, it takes one int called n (a parameter), and it gives back an int. return hands the result to whoever called it.
You have used one all along: main is the function Go runs first. In these lessons a func stands above main, and the loose lines under it are the inside of main.
func double(n int) int {
return n * 2
}
func main() {
fmt.Println(double(4)) // 8
}Concept
return is not print
fmt.Println shows a value on the screen, and that is all. return hands a value back to the line that called the function, which can store it, add to it or pass it on.
return also ends the function on the spot: no line after it runs.
A function that only does something, such as printing, needs no result type.
func add(a, b int) int {
return a + b
}
total := add(2, 3) // total is 5
fmt.Println(total * 10) // 5010 more exercises in the app
- 4× type the answer
- 1× fill the blanks
- 3× multiple choice
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.