Functions

View saved

Define a function

Types are required on parameters. The return type follows ->.

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

fn main() {
    println!("{}", add(2, 3));
}

Statements vs expressions

The last expression without a semicolon is returned.

fn double(n: i32) -> i32 {
    let result = n * 2;
    result
}

Early return

Use return when exiting early; otherwise prefer expression style.

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

Function tips

  • Keep ownership clear: take T, &T, or &mut T deliberately
  • Name functions with snake_case
  • Extract helpers when main grows
  • Macros like println! are not ordinary functions

Comments

One comment per signed-in account. Comments are saved with this page’s URL.