Bitpath

Lesson 1 · Unit 03

Defining functions

Parameters, results, return against print, several results, and scope.

13 exercisesabout 3 min

What you practise

  • Typed parameters and results, return against 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?

Go
func double(n int) int {
  return n * 2
}

fmt.Println(double(4))
fmt.Println(double(10))

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.

Go
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.

Go
func add(a, b int) int {
  return a + b
}

total := add(2, 3)      // total is 5
fmt.Println(total * 10) // 50

10 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.

One email when Bitpath is ready to try. Nothing else. Privacy