Bitpath

Lesson 1 · Unit 03

Defining functions

Parameters, results, and one function calling another

13 exercisesabout 3 min

What you practise

  • Typed parameters and the return type, the last expression is the result, the semicolon that changes it, one function calling another

Try a question from this lesson

Pick one

Above main sits a second piece of code, named double. Writing double(4) runs it with n as 4. What prints?

Rust
fn double(n: i32) -> i32 {
    n * 2
}

fn main() {
    println!("{}", double(4));
}

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Anatomy of a function

n: i32 is the parameter: the input, with its type. -> i32 is the type of the result the function hands back. The braces hold the work.

double(4) calls the function. The 4 is the argument: it becomes n.

main is a function too. In our short snippets, the lines below a function are inside main.

Rust
fn double(n: i32) -> i32 {
    n * 2
}
println!("{}", double(4));
println!("{}", double(10) + 1);

Concept

The last line is the result

A function hands back the value of its last line, when that line has no semicolon.

return hands a value back at once and leaves the function. Use it to leave early.

A function without -> hands back nothing. It is called for what it does, such as printing.

Rust
fn sign(n: i32) -> i32 {
    if n < 0 {
        return -1;
    }
    1
}
println!("{} {}", sign(-8), sign(3));

10 more exercises in the app

  • 3× type the answer
  • 2× 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