Hi
I am totally new to rust and started reading the rust book (The Rust Programming Language - The Rust Programming Language).
I am trying to wrap my head around the section "Syntax and Semantics", "Functions", subsection Expressions vs. Statements where it explains that:
-
expressions return a value, and expressions are everything that isn't a statement
-
There are 2 kinds of statements: declaration statements and expressions statements.
-
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...
- 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