expressions return values while statements do not.
There are two kinds of statements, declaration statements and expression statements
everything else in Rust is an expression.
the statement x + 1;
does not return a value.
Declaration statements
using let
to introduce a binding is not an expression. so this code does not work:
The compiler is telling us here that it was expecting to see the beginning of an expression, and a let
can only begin a statement, not an expression.
Note that assigning to an already-bound variable (e.g. y = 5) is still an expression, although its value is not particularly useful. Unlike other languages where an assignment evaluates to the assigned value (e.g. 5 in the previous example), in Rust the value of an assignment is an empty tuple () because the assigned value can have only one owner, and any other returned value would be too surprising:
Early Returns
you can have your functions perform an early return by using the return
keyword.
Diverging functions
you can also create variable bindings which point to functions: