Skip to the workspace
Pebellslearn by building
Introduction to Rust  ›  Lesson

Functions and Method Syntax

Functions and Method Syntax 12 minA function declares typed parameters and a return type and returns its last expression, while a method is a function in an impl block whose first parameter is self.

rust / Functions and Method Syntax

Explore each scene at your own pace.

01 · The rule

The rule

Functions and Method Syntax

A function declares typed parameters and a return type and returns its last expression, while a method is a function in an impl block whose first parameter is self.

Compare final expressions with statements and distinguish methods from associated functions.

The library program keeps computing the same things: the late fee for a book, a short summary line for a catalogue entry. Functions give those calculations a name. Rust functions look plain, with one quiet rule about the last line that trips up every newcomer.

The rule

Types on every parameter; the last expression, with no semicolon, is returned.

fn late_fee(days: u32) -> u32 {
    days * 10
}
  • fn starts a function; names use snake_case.
  • Every parameter must have a type: days: u32. Rust never guesses these.
  • -> u32 is the return type. Leave it out when nothing useful is returned.
  • The final expression days * 10, with no semicolon, is the return value. return exists for leaving early, but the last line normally needs no keyword.

Add a semicolon and days * 10; becomes a statement that produces nothing, written () and called "unit". The function then promises u32 but gives (), and the compiler rejects it.

Methods are functions attached to a type inside an impl block. Their first parameter is self in one of three forms:

struct Book { title: String, pages: u32 }

impl Book {
    fn new(title: &str, pages: u32) -> Book {   // associated function: no self
        Book { title: title.to_string(), pages }
    }
    fn is_long(&self) -> bool {                 // reads the book
        self.pages > 400
    }
    fn add_pages(&mut self, extra: u32) {       // changes the book
        self.pages += extra;
    }
}

let mut book = Book::new("Iron Tides", 380);
book.add_pages(30);
println!("{}", book.is_long()); // true

&self borrows to read, &mut self borrows to change, plain self takes the value over. Functions with no self, like new, are called on the type with ::.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.