Rust Tutorial · Rust Basics · Lesson 6 of 29

Rust Functions

Define functions with parameters and return types, and return values with expressions.

Create a free account to save this page, take notes and track your progress. Sign in

Defining functions

Parameters need types; the return type follows ->. The last expression is returned (no return needed); return is used for early exits.

Parameters, return types and early return
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?

  1. Only with the return keyword
  2. Its last expression, written without a semicolon
  3. By assigning to result
  4. Through an out parameter
Show answer

Answer: Its last expression, written without a semicolon

Was this page helpful?