Sub topic 2
Statements versus expressions
Rust code is built from two kinds of pieces: statements and expressions. The difference decides when a function returns a value, why if can appear on the right side of a let, and why one stray semicolon can break a function that looks correct. This chapter assumes you can build and run a program with cargo and know let, let mut, and the primitive types. It also assumes you have seen a simple function definition.
The two definitions
An expression evaluates to a value. A statement performs an action and does not produce a value you can use.
Rust has two kinds of statement that matter here:
- A
letstatement binds a name to a value, as inlet x = 5;. - An item declaration defines something like a function, struct, or
useinside a block.
A third form sits between the two. An expression followed by a semicolon is an expression statement. Rust evaluates the expression, then throws the value away.
Most of Rust is expressions. Literals, arithmetic, function calls, macro calls, blocks, if, match, and loop are all expressions.
| Construct | Kind | Value |
|---|---|---|
| `5`, `x + 1`, `add(2, 3)` | Expression | The computed value |
| `{ ... }` block | Expression | Its final expression, or `()` |
| `if`, `match`, `loop` | Expression | The value of the chosen branch or the `break` |
| `println!("hi")` | Expression | `()` |
| `a = 5` | Expression | `()` |
| `let x = 5;` | Statement | None |
| `fn helper() {}` | Item (statement) | None |
| `x + 1;` | Expression statement | Discarded |
Blocks are expressions
A block is code between { and }. It can contain any number of statements, followed by one optional final expression with no semicolon. That final expression is the tail expression, and its value becomes the value of the whole block.
fn main() {
let y = {
let x = 3;
x + 1
};
println!("{y}");
}The inner let x = 3; is a statement. The x + 1 has no semicolon, so it is the tail expression. The block evaluates to 4, and y receives that value. The name x exists only inside the block.
A function body is also a block, which explains why functions return their last expression:
fn square(x: i32) -> i32 {
x * x
}
fn square_explicit(x: i32) -> i32 {
return x * x;
}
fn main() {
println!("{} {}", square(4), square_explicit(4));
}Both functions behave the same. The first uses the tail expression. The second uses return, which is usually reserved for leaving a function early. Idiomatic Rust uses the tail expression when the value comes at the end.
The unit type and the semicolon
When a block has no tail expression, its value is (), called the unit type and pronounced "unit". It has exactly one value, which is also written (). Rust uses it wherever there is nothing meaningful to return.
A function declared without -> returns (). A semicolon turns an expression into a statement and discards its value, so a trailing semicolon changes what a block evaluates to:
fn main() {
let with_value = {
let t = 2;
t + 3
};
let without_value = {
let t = 2;
println!("t is {t}");
};
println!("{with_value} {:?}", without_value);
}This prints t is 2 and then 5 (). The first block ends in t + 3, so it has type i32. The second ends in a statement, so its type is (). The {:?} format prints () because () supports debug formatting but not the plain {} format.
Where semicolons are required
Rust needs a semicolon to end an expression statement, with one exception. These expressions are block-like: blocks, if, match, loop, while, and for. They may stand alone as a statement without a semicolon, as long as their type is ().
fn main() {
let n = 7;
if n > 5 {
println!("big");
}
let label = if n > 5 { "big" } else { "small" };
println!("{label}");
}The first if needs no semicolon because it is block-like and has type (). The second one sits on the right of a let, so the let statement needs its semicolon. A non-block expression in the middle of a block must end in a semicolon. Writing x + 1 followed by another line is a syntax error.
Assignment is an expression of type ()
In C, a = b = 5 assigns to both variables because assignment produces the assigned value. In Rust, assignment is an expression but its value is always ():
fn main() {
let mut a = 1;
let r = a = 5;
println!("{a} {:?}", r);
}This prints 5 (). The variable r holds the unit value, not 5. Chained assignment therefore does not work as it does in C. This design also avoids the C mistake of writing = where == was meant, because if a = 5 would be a type error.
let is different. It is a statement, so it cannot appear inside an expression. Code like let x = (let y = 6); does not compile. Related forms such as if let are special syntax that you will meet in a later chapter.
Items inside blocks
You can declare functions, structs, and constants inside any block. These items are statements in the sense that they produce no value, and they are visible only inside that block:
fn main() {
fn helper(x: i32) -> i32 {
x + 1
}
println!("{}", helper(1));
}Use this for small helpers that nothing else needs. An inner function cannot capture local variables from the surrounding block. Closures, covered later in this tutorial, can.
return versus the tail expression
return is an expression too. Its type is !, the "never" type, because control leaves the function and never produces a value at that spot. Because ! can stand in for any type, a block that ends by diverging type-checks against any declared type:
fn first_or_zero(v: &[i32]) -> i32 {
if v.is_empty() {
return 0;
}
v[0]
}
fn main() {
println!("{}", first_or_zero(&[]));
println!("{}", first_or_zero(&[9, 8]));
}The if block has type () and the statement return 0; has a semicolon, so everything type-checks. The tail expression v[0] supplies the normal return value. The pattern here is to return early for the special case, then fall through to the tail expression. A later chapter covers the never type in full.
Common errors
- Semicolon on the tail expression. The body evaluates to
()and the function return type mismatches. Remove the semicolon. - Missing semicolon mid-block. A non-block expression followed by more code is a syntax error. Add the semicolon.
- Branches with different types. An
if/elseused as a value needs the same type in each branch.if c { 1 } else { "one" }is rejected. Putting a semicolon after the number in one branch makes that branch(), which causes the same error. - Expecting an assigned value. Using
a = 5as a value gives you(). - Using
letas a value. Aletbinding does not evaluate to anything, so it cannot be nested in another expression.
Exercise
The function below fails to compile with "mismatched types: expected i32, found ()". Explain why, and give the smallest change that fixes it. fn double(x: i32) -> i32 { x * 2; }
Show answer
The semicolon turns x * 2 into an expression statement, so its value is discarded. The block then has no tail expression and evaluates to (), which does not match the declared return type i32. Remove the semicolon so the body is x * 2. Writing return x * 2; also works.
Exercise
What do a and b hold after this code runs, and what are their types?
let mut c = 0;
let a = { c += 1; c };
let b = { c += 1; };
Show answer
a is 1 of type i32, because the block ends in the tail expression c. b is (), the unit type, because the block ends with a semicolon and has no tail expression. The variable c is 2 afterwards.