Learn/Rust/6. Functions
Lesson 6 of 15
Sign in

Rust, lesson 6

Functions

A function packages a piece of work under a name. You have been writing main all along; now you will write your own and call them.

Defining and calling

  • Every parameter needs a type: c: f64. Rust never guesses parameter types.
  • The return type comes after ->. A function that returns nothing leaves it out.
  • Function names use snake_case, and functions can be defined before or after the code that calls them.

The last expression is the result

Look closely: c * 9.0 / 5.0 + 32.0 has no semicolon. In Rust, a block's value is its final expression, so the function returns it. Adding a semicolon would turn it into a statement that produces () (the "unit" value, meaning nothing), and the compiler would complain that the function does not return an .

2 exercises to try what you just read.

Exercise 1

Lowest and highest

Press Ctrl Enter or Check to test your code.

Exercise 2

Letter grades

Press Ctrl Enter or Check to test your code.

f64

You can still use return to leave early, typically inside a condition:

Idiomatic Rust uses return only for early exits and lets the final expression do the rest.

Returning several values with a tuple

A tuple groups a fixed number of values, possibly of different types, in parentheses. Return one to hand back several results, and take it apart with a pattern:

You can also index a tuple: pair.0, pair.1.

Arguments and copies

Simple values such as numbers, bool and char are copied when you pass them to a function. Changing the parameter does not affect the caller:

Text and collections behave differently: they are moved or borrowed. For now, pass text as &str (a borrowed string slice) and return new values instead of changing arguments. Lesson 14 explains ownership in full.

Scope and blocks

A variable lives from its let until the end of the block { ... } that contains it. Each call to a function gets fresh local variables. A block is itself an expression, so you can compute a value in a small private scope:

Functions cannot see local variables of other functions, including main's. Pass what they need as parameters and return results. This makes every function easy to test on its own.

Further reading

  • The Rust Book: Functions
  • The Rust Book: The tuple type
  • Rust by Example: Functions

Write a function min_max(a: i64, b: i64, c: i64) -> (i64, i64) that returns the smallest and the largest of three numbers. Read three integers and print the two results separated by a space. Try if expressions (or the .min() / .max() methods) inside your function.

Sample input:

Sample output:

Write a function grade(score: u32) -> char that returns 'A' for 90 and above, 'B' for 80–89, 'C' for 70–79, 'D' for 60–69 and 'F' below 60. Read scores (separated by whitespace) until the input ends, and print score: letter for each.

Sample input:

Sample output:

fn to_fahrenheit(c: f64) -> f64 {
    c * 9.0 / 5.0 + 32.0
}

fn main() {
    println!("{}", to_fahrenheit(100.0)); // 212
}
fn safe_divide(a: i32, b: i32) -> i32 {
    if b == 0 {
        return 0;
    }
    a / b
}
fn div_mod(a: i32, b: i32) -> (i32, i32) {
    (a / b, a % b)
}

let (q, r) = div_mod(17, 5);
println!("{q} {r}"); // 3 2
fn double(mut n: i32) -> i32 {
    n *= 2; // changes only the local copy
    n
}
fn shout(word: &str) -> String {
    word.to_uppercase() + "!"
}
let area = {
    let w = 4;
    let h = 5;
    w * h
}; // w and h no longer exist here
8 3 11
3 11
95 72 40
95: A
72: C
40: F