Is `return 5;` a statement or expression in Rust?

You can find out via Rust macros:

macro_rules! expr_or_stmt {
    ($_:expr) => {
        "expr"
    };
    ($_:stmt) => {
        "stmt"
    };
}

fn main() {
    dbg!(expr_or_stmt!(return 5));
}

It prints "expr", as you can see on the playground.


The wording there is inexact. When it says "a statement...will not return a value", it means that a statement is not processed by evaluating it into a final value (as an expression is), but is rather processed by executing it. In the case of a return statement, the execution takes the form of exiting the current function, passing the return value to the calling function.

return 5; is most certainly a statement.

Tags:

Rust