Rust Tutorial · Rust Basics · Lesson 6 of 29
Rust Functions
Define functions with parameters and return types, and return values with expressions.
Defining functions
Parameters need types; the return type follows ->. The last expression is returned (no return needed);
return is used for early exits.
fn shipping_cost(weight_kg: f64, express: bool) -> f64 {
if weight_kg <= 0.0 {
return 0.0;
}
let base = 4.99 + weight_kg * 1.5;
if express { base * 2.0 } else { base }
}
fn describe(name: &str, cost: f64) -> String {
format!("{name}: {cost:.2} EUR")
}
fn main() {
println!("{}", describe("standard", shipping_cost(2.0, false)));
println!("{}", describe("express", shipping_cost(2.0, true)));
println!("{}", describe("empty", shipping_cost(0.0, true)));
}
Output
standard: 7.99 EUR express: 15.98 EUR empty: 0.00 EUR
Run this on your computer — see “Get Started” for setup.
Test yourself
How does a Rust function usually return a value?
Only with the return keywordIts last expression, written without a semicolonBy assigning to resultThrough an out parameter
Show answer
Answer: Its last expression, written without a semicolon