Is there an elastic range?

let x

while ...
    println SOMETHING

for i in 0..x
    println SOMETHING // again. that thing. extra x times

Is there more elegant way for my loops?
(I want to use print only once)

Please describe what you are trying to do in more detail. I have no idea what you mean by an "elastic range".

1 Like
fn main() {
    let x = 3;
    let mut dotdotdot = true;
    
    let mut x_times = 0..x;
    while dotdotdot || x_times.next().is_some() {
        println!("whatever");
        dotdotdot = false;
    }
}
2 Likes

In while I do not know how many times.
In for I do know how many times.

So, I want to combine WHILE ... with FOR ...
Is it possible ? Or is my approach normal ?

Excuse me for confusing caption.

Note that my solution will still evaluate dotdotdot every loop iteration, modulo compiler optimizations, so if it's something that involves expensive side effects to evaluate you should do something slightly different.

1 Like

The obvious answer is to make a function.

fn main() {
    let x = 3;
    let mut dotdotdot = true;

    let x_times = 0..x;
    while dotdotdot {
        do_something();
        dotdotdot = false;
    }

    for _ in x_times {
        do_something();
    }
}

fn do_something() {
    println!("whatever");
}

Closure works as well.

3 Likes

There is no language feature specifically for this, so you’ll have to handwrite something.

I don’t think it’s much better than using a function or closure, and I feel that in general you’ll want to split as suggested above, however, it’s also possible to combine a few iterators together and achieve something similar. For instance:

fn main() {
    let n = 3;

    core::iter::repeat(0)
        .take_while(|_| some_condition())
        .chain(0..n)
        .for_each(|_| println!("something"));

    // OR

    for _ in core::iter::repeat(0)
        .take_while(|_| some_condition())
        .chain(0..n)
    {
        println!("something2")
    }
}

Execute here: Rust Playground

Depending on what you’re trying to do, you may prefer one or the other.

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.