Expressions vs Statements
In this page:
What Is a Statement
A statement performs an action but does not itself evaluate to a value. Variable declarations with let are statements -- you cannot use let x = 5; as a value.
Example: What Is a Statement
fn main() {
let x = 5; // this whole line is a statement
println!("x = {}", x);
}
Login to try C/C++/Java/PHP code in the editor
What Is an Expression
An expression evaluates to a value. Simple examples include 5 + 6 or a function call like square(4), both of which produce a usable value.
Example: What Is an Expression
fn main() {
let sum = 5 + 6; // 5 + 6 is an expression
println!("sum = {}", sum);
}
Login to try C/C++/Java/PHP code in the editor
Blocks as Expressions
A block enclosed in { } is itself an expression: if its final line has no trailing semicolon, that line's value becomes the value of the whole block.
Example: Blocks as Expressions
fn main() {
let y = {
let a = 3;
a * a // no semicolon: this is the block's value
};
println!("y = {}", y);
}
Login to try C/C++/Java/PHP code in the editor
Why the Semicolon Matters
Adding a semicolon after an expression turns it into a statement that evaluates to the unit type (). This is why forgetting or adding a stray semicolon on a function's last line changes whether it returns a value.
Example: Why the Semicolon Matters
fn plus_one(x: i32) -> i32 {
x + 1 // no semicolon, so this value is returned
}
fn main() {
println!("{}", plus_one(4));
}
Login to try C/C++/Java/PHP code in the editor
- Adding a semicolon to what was meant to be the returned tail expression, accidentally turning it into a statement that returns
(). - Assuming an
if/matchblock always needsreturnto produce a value, when the tail expression is often enough. - Trying to assign the result of a statement (like a
letbinding) to another variable, since statements do not produce a usable value.
- Statements perform an action and do not return a value; they typically end with a semicolon.
- Expressions evaluate to a value, such as
5 + 6or a block ending in a value-producing line without a semicolon. - Blocks
{ ... }are themselves expressions if their last line has no semicolon. - Understanding this distinction explains why removing or adding a semicolon can change a function's behavior.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: