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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With