Expression statements


#1

Hi

I am totally new to rust and started reading the rust book (https://doc.rust-lang.org/book/).

I am trying to wrap my head around the section “Syntax and Semantics”, “Functions”, subsection Expressions vs. Statements where it explains that:

  1. expressions return a value, and expressions are everything that isn’t a statement

  2. There are 2 kinds of statements: declaration statements and expressions statements.

  3. How does a statement can be a function’s return value?


Regarding expressions statements it says:

Its purpose is to turn any expression into a statement.

I guess that the “expressions statement” refers to the x + 1 in the example’s code:

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

If I understand the definition: x+1; is an expression (that would return the value ()), but by removing the semicolon, it’s turned into a expression statement. But a statement doesn’t return a value. So how come the function gets returned a value, if the statement doesn’t return a value?

From my question it seems like I am missing something obvious somewhere…

  1. statements follow other statements

In practical terms, Rust’s grammar expects statements to follow other statements. This means that you use semicolons to separate expressions from each other.

In the example, how is the statement x+1 follows another statement? Ok in the example code, this is the only line in the function’s body, but if we had

fn add_one(x: i32) -> i32 {
    println!('hello');
    x + 1
}

does this mean println! is a statement?

Regard
Vangelis


#2

I think it’s the other way – x+1 is an expression, and x+1; is an expression statement. So the function does return this value, since it was not a statement.

Yes, since it has a semicolon, it’s a statement. And if you have a block like { statement; statement; expression } then that final expression becomes the value for the whole block.


#3

Also, a block like { statement; statement; } without a final expression has the value (), the same as if you’d written { statements...; () }.


#4

Thanks @cuviper, it now makes makes much more sense. It seems I got it completely wrong!


#5

Is println! an expression or a statement?

The author said println! is a macro expanding to an expression. Could you please explain why you get a different understanding? Thank you.


#6

I suppose my answer was a little loose, but note the qualifier I used, “since it has a semicolon”. A println!(...) alone produces an expression, but adding a semicolon makes it an expression statement.


#8

Thanks, I get it