JamesThomasMoon
JamesThomasMoon

Reputation: 7164

Is there an iterator method like skip_while that keeps skipping?

The Rust Iterator method skip_while stops skipping elements (always returns elements) after the first failed test. How to continue skipping (i.e. do not "turn off" skipping)?

Rust iterator method skip_while() documentation reads

skip_while() takes a closure as an argument. It will call this closure on each element of the iterator, and ignore elements until it returns false.

After false is returned, skip_while()’s job is over, and the rest of the elements are yielded.

I want skip_while's "job to not be over" after seeing a false. What is a Rustic way to use iterators to accomplish this?

So for example, this code

fn main() {
    let lines = [
        "",
        "a",
        "",
        "b",
        "",
        "c",
    ];
    for line in lines.iter().skip_while(|x| x.is_empty()) {
        println!("line is {:?}, {:?}", line, line.is_empty());
    }
}

prints

line is "a", false
line is "", true
line is "b", false
line is "", true
line is "c", false

I would like code that prints

line is "a", false
line is "b", false
line is "c", false

How to do this using iterators and adapter methods?

Upvotes: 0

Views: 311

Answers (1)

JamesThomasMoon
JamesThomasMoon

Reputation: 7164

Use the filter method.

Code snippet

fn main() {
    let lines = [
        "",
        "a",
        "",
        "b",
        "",
        "c",
    ];
    for line in lines.iter().filter(|x| !x.is_empty()) {
        println!("line is {:?}, {:?}", line, line.is_empty());
    }
}

prints

line is "a", false
line is "b", false
line is "c", false

Upvotes: 3

Related Questions