Why does my Loop skip control flow?

⚓ Rust    📅 2025-06-26    👤 surdeus    👁️ 6      

surdeus

Warning

This post was published 47 days ago. The information described in this article may have changed.

The second loop wouldn't stop as if it passed an if, so I changed the location of the y variable, it should be inside the first loop and this code would work. I just can't imagine why this happens, in the order of the first loop then the second loop, because the control flow doesn't work then the second loop becomes an unlimited process and the first loop will never finish.

Is it because the y variable is too far away (wrapped in loop with loop) so that the control flow cannot check the value of Y how much?

fn main (){
   let mut x: i32 = 0;
   let mut y =  5;


   'first_loop: loop {

      println!("x = {x}");
      x += 1;

   'second_loop: loop {
      println!("y = {y}");
      y -= 1;
      if y == 2 {break 'second_loop}
      if x == 10 {break 'first_loop}

   }
   }
}

3 posts - 3 participants

Read full topic

🏷️ rust_feed