3 Statements and Expressions in Rust
fn main() {
let x = 1u32;
// expression ;
x;
x + 1;
15;
let x = 5;
//block expression ;
{
5 ;
}
let y = {
let x = x * x;
2 * x
};
let z = {
// The semicolon suppresses this expression and `()` is assigned to `z`
2 * x;
};
println!("x is {:?}", x);
println!("y is {:?}", y);
println!("z is {:?}", z);
}
The same variable name can be defined multiple times
The inner scope defines a new variable x that shadows the outer x.
As a result, the value of x defined within the inner scope does not affect the value of the x in the outer scope
The result of the block expression is 2 * x, which evaluates to 50
The result of the block expression is ‘()‘
fn main() {
let y = 6;
let y = {
let x = 3;
x + 1
};
println!("The value of y is: {y}");
}
Statements are instructions that perform some action and do not return a value.
Expressions evaluate to a resultant value.
Rust is an expression-based language, which is an important distinction to understand (as opposed to other languages).
This line is a statement. The let y = 6 statement does not return a value
The 6 in the statement let y = 6; is an expression that evaluates to the value 6.
The code block {
let x = 3;
x + 1
} is a block expression.