January 2019
Beginner to intermediate
554 pages
13h 31m
English
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.rsfn 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.
Read now
Unlock full access