Rust Functions
A function is a named block of code that performs one job. Functions let you write logic once and reuse it, give a meaningful name to a piece of work, and break a big program into small, understandable parts.
You have already been writing one function in every program: main. Now it's time to write your own.
Defining and calling a function
Functions are declared with the fn keyword, followed by a name, parentheses and a body in curly braces. Rust uses snake_case for function names: lowercase words separated by underscores.
fn print_banner() {
println!("=====================");
println!(" Welcome to ExcelTAD");
println!("=====================");
}
fn main() {
print_banner();
println!("Let's learn about functions.");
print_banner();
}=====================
Welcome to ExcelTAD
=====================
Let's learn about functions.
=====================
Welcome to ExcelTAD
=====================
It does not matter whether print_banner is defined above or below main — Rust finds functions anywhere in the file.
Parameters
Parameters let you pass values into a function. Each parameter needs a name and a type; Rust never guesses parameter types.
fn greet(name: &str, times: u32) {
for _ in 0..times {
println!("Hello, {}!", name);
}
}
fn main() {
greet("Ana", 2);
greet("Ben", 1);
}Hello, Ana!
Hello, Ana!
Hello, Ben!
&str is a borrowed piece of text (a string slice) and u32 is an unsigned 32-bit integer. The _ in the for loop means "I don't need the loop counter".
Return values
To send a value back, declare the return type after an arrow ->. The last expression in the body — written without a semicolon — is the value the function returns.
fn square(x: i32) -> i32 {
x * x
}
fn area_of_rectangle(width: f64, height: f64) -> f64 {
width * height
}
fn main() {
let s = square(7);
println!("7 squared is {}", s);
println!("Area: {}", area_of_rectangle(2.5, 4.0));
}7 squared is 49
Area: 10
Note: If you add a semicolon —
x * x;— the line becomes a statement that produces nothing, and the compiler reports "mismatched types: expectedi32, found()". This is one of the most common beginner mistakes, and the compiler even suggests removing the semicolon.
Statements vs expressions
This distinction matters a lot in Rust:
| Produces a value? | Example | |
|---|---|---|
| Expression | yes | 5, a + b, square(3), if x > 0 { 1 } else { -1 } |
| Statement | no | let y = 6;, println!("hi"); |
Because a block { ... } is also an expression, you can compute a value in several steps and use the last line as the result.
Returning early with return
You can leave a function before the end with the return keyword. This is useful for handling special cases first.
fn describe_age(age: u32) -> &'static str {
if age < 13 {
return "child";
}
if age < 20 {
return "teenager";
}
"adult"
}
fn main() {
for age in [8, 15, 42] {
println!("{} -> {}", age, describe_age(age));
}
}8 -> child
15 -> teenager
42 -> adult
The return type &'static str means "a string slice that lives for the whole program" — string literals like "child" are exactly that. You'll learn about the 'static part in the Lifetimes chapter.
Returning more than one value
A function returns a single value, but that value can be a tuple holding several pieces:
fn min_max(numbers: &[i32]) -> (i32, i32) {
let mut min = numbers[0];
let mut max = numbers[0];
for &n in numbers {
if n < min {
min = n;
}
if n > max {
max = n;
}
}
(min, max)
}
fn main() {
let data = [4, -2, 17, 9, 0];
let (low, high) = min_max(&data);
println!("Lowest: {}, highest: {}", low, high);
}Lowest: -2, highest: 17
&[i32] is a slice — a borrowed view of a list of i32 values. It accepts arrays and vectors of any length.
Summary
- Declare functions with
fn name(param: Type) -> ReturnType { ... }. - Every parameter needs a type annotation.
- The final expression (no semicolon) is the return value;
returnleaves early. - Functions with no
->return the unit type().
Test yourself
What does this function return? fn f() -> i32 { 10 }
- Nothing
10()- It does not compile
Why does fn double(x: i32) -> i32 { x * 2; } fail to compile?
xmust be mutable- The semicolon turns the last line into a statement, so the function returns
() - Functions cannot multiply
- Parameters can't be named
x
Which is a correct function signature that takes two f64 values and returns an f64?
fn avg(a, b) -> f64fn avg(a: f64, b: f64): f64fn avg(a: f64, b: f64) -> f64func avg(f64 a, f64 b) f64