← Back to Rust Course | Chapter 4: Functions | Lesson 2 of 6

Parameters and Return Values

Functions can take in information to work with, and hand back an answer when they finish.

Function Parameters

Parameters let a function accept input values. Each parameter must be given an explicit type, since Rust never infers function signatures.

Example: Function Parameters

markup
fn greet_person(name: &str) {
    println!("Hello, {}!", name);
}

fn main() {
    greet_person("Ada");
}

Returning a Value

A function's return type is declared after an arrow ->. The final expression in the function body, written without a trailing semicolon, becomes the returned value.

Example: Returning a Value

markup
fn square(n: i32) -> i32 {
    n * n
}

fn main() {
    println!("Square of 6 is {}", square(6));
}

Multiple Parameters

Functions can accept several parameters, separated by commas, each with its own type. They are used inside the function body just like local variables.

Example: Multiple Parameters

markup
fn add(a: i32, b: i32) -> i32 {
    a + b
}

fn main() {
    println!("3 + 4 = {}", add(3, 4));
}

Early Return with the return Keyword

The return keyword immediately exits a function with a given value, which is useful for handling special cases early before the main logic of the function runs.

Example: Early Return with the return Keyword

markup
fn absolute_value(n: i32) -> i32 {
    if n < 0 {
        return -n;
    }
    n
}

fn main() {
    println!("abs(-8) = {}", absolute_value(-8));
}
Common Mistakes
  1. Adding a semicolon after the final expression in a function, which turns it from a returned value into a discarded statement.
  2. Forgetting to write -> Type when a function is meant to return a value, causing a compile error at the return site.
  3. Using the return keyword everywhere out of habit when the idiomatic tail-expression style would be cleaner.
Chapter Summary
  • Parameters are declared as name: Type inside the parentheses, and every parameter must have an explicit type.
  • A function's return type is written after ->, and the last expression (without a semicolon) is returned automatically.
  • The return keyword can exit a function early with a value, useful inside conditionals.
  • A function with no return type implicitly returns the unit type ().
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.