using an index variable for multiple while loops

120 Views Asked by At

I have multiple while loops inside a for loop, and I want to use the index of the current loop as the starting value of both while loops like this:

for n in 0..10 {
    let mut j = n;
    while j > 0 {
        j/=2;
    }
    j = n;
    while j > 0 {
        j/=2;
    }
}

I've heard of shadowing but I can't think of a way to have it limited to the inside of the while loop and also be the condition for the while loop. I feel like there should be a better way to do this but I can't find it anywhere. is this really the correct way to do this or is there a nicer way I'm not seeing?

2

There are 2 best solutions below

0
Kaplan On

What exactly is to be achieved is not quite clear. If you want to run through the for loop with a new starting value, use a 'label for the for loop.

'outer: for n in 0..10 {
    let mut j = n;
    if j > 0 {
        while j > 0 {
            j /= 2;
            println!("{j}");
        }
        continue 'outer; 
    }
    j = n;
    if j > 0 {
        while j > 0 {
            j /= 2;
            println!("{j}");
        }
        continue 'outer; 
    }
}

Playground

0
Yoric On

I'm not entirely sure what you intend to do, so if you could edit your question to clarify it, that would help us help you!

Are you looking for a way to not reuse the same j between the two while loops? You could write:

for n in 0..10 {
    let mut j = n;
    while j > 0 {
        j/=2;
    }
    let mut j = n; // That's shadowing.
    while j > 0 {
        j/=2;
    }
}