Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logic about return in rust

Tags:

rust

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.

  1. In this case line break counter * 2; has this and return value, why?

  2. If I drop this ";" in thia line i get the same result, why?

  3. 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}");
}
like image 865
Mateusz Szymczak Avatar asked Apr 14 '26 20:04

Mateusz Szymczak


1 Answers

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

like image 194
cafce25 Avatar answered Apr 19 '26 01:04

cafce25



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!