I am just learning Rust and want to incrementally add values to a variable to see if I understood the difference between expressions and statements in Rust.
fn main() {
let mut x:i32 = 1;
x += for num in 1..4 {
num
};
println!("{0}",x);
}
This gives a compiler error:
error[E0308]: mismatched types
--> src/main.rs:6:9
|
6 | num
| ^^^ expected `()`, found integer
Loop expressions do not yield a value (they yield ()) unless they are given a break with a value. And for loops are not eligible for break with a value.
Are you accustomed to functional programming or mathematical expressions on lists/vectors where you can sum a range of values? A for loop can't be used for that, but Rust iterators can be, if you're interested.
thanks all of you for your answer. But I thought that every expression returns a value as it is written in the Rust book Functions - The Rust Programming Language under statements and expressions. Shouldn't the loops be named loop statements then since they do not return a value?
They do return a value. That value is just (), aka "unit".
Demonstration of putting the value of a for loop expression into a variable: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=d040b446a0cda138f6ce8e865ef95fd3. (There's no reason to do that, but it's possible. And it matters in some corner cases, like how you don't need braces around the whole for loop if it's the only thing in a match. As in it doesn't need to be { for i in 0..10 { ... } } -- the body of the loop of course always needs them.)
The difference between a statement and an expression is usually grammatical (syntactic if your prefer)
Expressions can contain nested expressions arbitrarily, whereas a statement must appear at the outermost level.
Naturally, an expression needs to evaluate to some value in order to nest it, but this is not what decides whether it is an expression or not.