It's easy rust code, which is from rustbook on rust website. In rust if line is without ";" at the end it works like a return.
In this case line
break counter * 2;
has this and return value, why?
If I drop this ";" in thia line i get the same result, why?
Even if I add this ";" to the next line i mean }; i get the same result, why?
I try to understand it, but can't catch this logic.
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("Zmienna result wynosi {result}");
}
break EXPRESSION, when reached, immediately terminates the closest loop1 (that is moves the program flow to just after the loops closing brace }) and the whole loop {…} evaluates to the value of EXPRESSION (always counter * 2 = 10 * 2 = 20 in your example), what comes after it does not matter at all.
1: or for or while but they don't allow breaking with expressions so that'd result in a compiler error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With