My Rust Deck

111 cards

Beginner - Basics

Question:

How do you return a value from a function in Rust?

Answer:

fn add(a: i32, b: i32) -> i32 {
    a + b  // No semicolon = implicit return
}

fn subtract(a: i32, b: i32) -> i32 {
    return a - b;  // Explicit return also works
}

fn main() {
    println!("5 + 3 = {}", add(5, 3));
    println!("5 - 3 = {}", subtract(5, 3));
}

Copy, paste and run the code above in Rust Playground.

Declare return type with ->. The last expression without a semicolon is the return value. Use return for early returns.

Read more in TRPL - Functions with Return Values.

Show Answer Back to Filters