Functions in Rust can return values. The return type is declared after an arrow (->). The return value is synonymous with the value of the final expression in the function body.
Rust
fn five() -> i32 {
5
}
fn main() {
let x = five();
println!("The value of x is: {x}");
}
The function five returns the value 5, and when called in main, the output will be:
Rust
The value of x is: 5
It's important to note that expressions in Rust do not include ending semicolons. Adding a semicolon turns an expression into a statement.
Rust
fn plus_one(x: i32) -> i32 {
x + 1
}
Here, x + 1 is an expression, and the function returns its value. Adding a semicolon at the end would turn it into a statement, resulting in a compilation error.