Functions
9 min · Rust
Package code under a name so you can reuse it.
Enemy 1 of 5
A function packages up a piece of logic under a name, so you can run it whenever you need it instead of retyping the same code. You've already been using one: fn main() is itself a function — it's just special because Rust calls it automatically when the program starts. You can define your own functions with the same fn keyword anywhere in the file.
Rust functions are strict about types: every parameter must declare what type it accepts, written as name: Type, and if the function hands a value back, the return type follows an arrow (-> Type) after the parameter list. In fn double(n: i32) -> i32, the function is named double, it takes one parameter n of type i32 (a 32-bit whole number), and it promises to return an i32. Unlike Python or JavaScript, Rust won't guess these types for you at the function boundary — this is one of the tradeoffs that lets the compiler catch type mistakes (like passing text where a number is expected) before the program ever runs.
Inside the body, return sends a value back to whoever called the function, and immediately stops the function from running any further code. You can also omit both return and the semicolon on the final line of a function to return that value implicitly — Rust supports this expression-based style, though using an explicit return like the example below is perfectly normal and arguably clearer while you're still learning.
Loading editor...