Functions

Programming Languages · Rust Basics · 12 min

Write your own functions with typed parameters and return values.

Your own function

A function is a named block of code you can run again and again. Make one with fn, outside main. Run it ("call" it) by writing its name and ():

fn wave() {
    println!("Hi!");
}

fn main() {
    wave();
}
  • Above main, write a function cheer that prints Go team!.

  • Call cheer twice from main.

Parameters

A parameter is a value you hand to a function. List them in the brackets, each with a name and a type:

fn greet(name: &str) {
    println!("Hello, {}!", name);
}

Now greet("Ada") prints Hello, Ada! and greet("Linus") prints Hello, Linus!. Rust always wants the types written here.

  • Write fn say_age(name: &str, age: u32) that prints the name, is, and the age, like Ada is 36.

  • In main, call say_age("Ada", 36) and then say_age("Linus", 54).

Returning a value

Functions can hand a value back. Write the type after ->. The last line, with no semicolon, is the value that comes back:

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

Then double(4) gives 8, which you can print or store.

  • Write fn add(a: i32, b: i32) -> i32 that returns a + b.

  • In main, print add(2, 3) and then add(10, 20).

Expressions: the missing semicolon

Why no semicolon? In Rust, n * 3 is an expression: it produces a value. Add a ; and it becomes a statement, which produces nothing, so the function has nothing to return.

You can write return n * 3;, but Rust programmers usually just leave the last expression bare. It's shorter.

  • Rewrite triple so its body is just n * 3, with no return and no semicolon.

  • Write fn square(n: i32) -> i32 in the same style (body n * n), then print square(5) in main.

Put it together: a tip calculator

Two small functions that work together. total can call tip to do part of its job. Functions calling functions is how big programs are built.

  • Write fn tip(amount: f64) -> f64 that returns amount * 0.25.

  • Write fn total(amount: f64) -> f64 that returns amount plus tip(amount).

  • In main, print Tip: 12 and Total: 60 by calling tip(bill) and total(bill).

More in Rust Basics

Previous: Data Types · Next: Control Flow