When writing Rust programs, it’s important to understand the difference between expressions and statements. Rust is an expression-based language, which means most things you write are expressions that produce a value.
Let’s break it down.
What is a Statement? #
A statement is an instruction that performs an action but does not return a value.
In Rust, the most common statements are:
For example:
fn main() {
let x = 5; // statement
let y = 10; // statement
println!("x is {}, y is {}", x, y); // statement
}
Code language: Rust (rust)In this example:
let x = 5;andlet y = 10;are statements.- They don’t evaluate to a value you can use directly.
If you try to do this:
let z = (let x = 5); // ❌ Error!Code language: Rust (rust)You’ll get an error, because let x = 5 is a statement, not an expression.
What is an Expression? #
An expression evaluates to a value.
- It can be part of a statement.
- Expressions don’t end with a semicolon
;if you want them to return a value.
Here are some examples of expressions:
- Math:
5 + 2 - Function calls:
square(4). - Blocks
{ }that return a value.
For example:
fn main() {
let a = 5 + 2; // expression inside statement
let b = square(4); // expression inside statement
println!("a = {}, b = {}", a, b);
}
fn square(n: i32) -> i32 {
n * n // expression (no semicolon here!)
}
Code language: Rust (rust)5 + 2is an expression.square(4)is an expression.- Inside
square, the last linen * nis also an expression that returns a value.
Note that If you put a semicolon after n * n;, it becomes a statement, and the function won’t return a value.
Expressions in Blocks #
Blocks { } can also be used as expressions!
fn main() {
let number = {
let x = 3;
let y = 4;
x + y // last expression returned
};
println!("number = {}", number); // number = 7
}
Code language: Rust (rust)- The block
{ let x = 3; let y = 4; x + y }is an expression. - Its value (
7) is assigned tonumber.
Summary #
- Statements: Do something but return no value.
- Expressions: Produce a value and can be used inside statements.
- Rust functions often return the value of the last expression in the body.
- Leaving off the semicolon makes something an expression; adding it turns it into a statement.