Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

I am not a nitpicker, but from Statements and expressions:

We’ve actually already used statements and expressions. Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. Let’s look at some examples.

......

Expressions do not include ending semicolons. If you add a semicolon to the end of an expression, you turn it into a statement, which will then not return a value. Keep this in mind as you explore function return values and expressions next.

So for return 5;, is it a statement or expression? If it is a statement, a statement should not return value; if it is an expression, an expression should not have an ending semicolon.

like image 201
Nan Xiao Avatar asked Sep 24 '18 08:09

Nan Xiao


2 Answers

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.

like image 110
Sneftel Avatar answered Oct 17 '22 02:10

Sneftel


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.

like image 2
passing_through Avatar answered Oct 17 '22 03:10

passing_through