I'm a little confused about this scene of loop and break

fn main(){
    let mut counter = 0;
    let result = loop{
        counter +=1;
        if counter == 10{

            //Whether or not I add ";" here, the result will compile and pass and output 20
            break counter * 2;

        }
    };
    println!("{}",result);
}

The version I am using now is 1.79.0,I don't know why

break followed by an expression within a loop, in addition to terminating the loop, causes the loop block to evaluate to the given expression. I'd give an example code snippet demonstrating that, but it'd look almost exactly like yours.

If you put the ; it will be considered as a statement, while if you don't put the ; it will be considered as an expression. In this case there's no difference because both have the same effect of diverging and exiting the loop with the given value.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.