Loop as an expression

In Rust, a loop is also an expression that returns () by default when we break out of it. The implication of this is that loop can also be used to assign value to a variable with break. For example, it can be used in something like this:

// loop_expr.rs

fn main() {
let mut i = 0;
let counter = loop {
i += 1;
if i == 10 {
break i;
}
};
println!("{}", counter);
}

Following the break keyword, we include the value we want to return and this gets assigned to counter variable when the loop breaks (if at all). This is really handy in cases where you assign the value of any variable within the loop after breaking from the loop and need to use it afterward.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset