Learn the difference between statements and expressions in Rust.
I'm learning Rust recently and I'm reading the Rust documentation. I found this page about statements and expressions. I think it's a good idea to write a blog about it.
In short
Function bodies are made up of a series of statements optionally ending in an expression.
In the above example, let x: i32 = 69;
end with a
semicolon, so it's a statement. It assigns the value
69
to the variable x
.
Function definitions are also statements; the entire example above is a statement in itself.
Statements do not return values. Therefore, you can’t assign a let statement to another variable. For example, the following code will not compile:
However, in other language like Python you can do this.
The assignment returns the value of the assignment.
You can write x = y = 69
and have both x and y have the
value 69.
Expressions do not include ending semicolons. If you add a semicolon
to the end of an expression, you turn it into a statement, and it
will then not return a value. In the following example,
j + 1
is an expression so it returns a value and assign
it to i
.
You can return early from a function by using the
return
keyword and specifying a value, but most
functions return the
last expression
implicitly. In this case,
x + 1
is the expression that we want to return.
If we place a semicolon at the end of the line containing
x + 1
, changing it from an expression to a statement.
This code will not compile:
Instead you will get an mismatched type error message like this:
implicitly returns `()` as its body has no tail or `return` expression
We will not cover what unit type ()
is in this blog. If
you are interested, you can read the Rust documentation about it
here.
To summarize, statements do not return values, but expressions do. 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 when writing Rust code. If you have any questions, feel free to leave a comment below. Thank you for reading!