Functions, statements and expressions

Typed parameters, return types, and why the last line of a function has no semicolon.

What you'll learn
  • Declare functions with typed parameters and a return type
  • Distinguish statements from expressions
  • Explain why adding a semicolon can break a function
fn print_func() {
    println!("This is a print from a function!");
}

fn arg_func(x: i32, y: i32) {
    println!("Value of x is {}, and value of y is {}", x, y);
}

fn return_func(x: i32) -> i32 {
    x + 1
}

fn main() {
    print_func();
    arg_func(2, 3);
    let x = return_func(2);      // 3
}

Every parameter needs a type — Rust infers types inside a function, but never across its signature, so the signature alone tells a reader (and the compiler) how to call it. The return type follows ->; a function without one returns (), the empty “unit” value. And, as the script’s comment says, order does not matter: main can call functions defined below it.

Statements and expressions

return_func has no return keyword and its last line has no semicolon. That is the most important syntax rule in Rust:

  • An expression evaluates to a value: x + 1, 5, a block { ... }, an if, a function call.
  • A statement performs an action and evaluates to nothing: let y = 6;, or any expression with a semicolon after it.

A function body is a block, and a block’s value is its final expression. So x + 1 is the return value. Add a semicolon — x + 1; — and the last line becomes a statement, the body evaluates to (), and the compiler reports a type mismatch: the function promised an i32 but returns (). The error even suggests removing the semicolon. The same rule makes if usable as a value in the previous lesson.

return still exists, and is the clear choice for leaving a function early, such as returning from the middle of a loop.

Try it yourself. Add the semicolon to x + 1; and read the error. Then write fn classify(n: i32) -> &'static str that returns "negative", "zero" or "positive" using if as the function’s final expression, with no return.

View source on GitHub →