Skip to content

Iterator#take_while consumes first falsy value #31318

Closed
@Mark-Simulacrum

Description

@Mark-Simulacrum

The take_while method on iterators consumes the first falsy value, instead of leaving it in the iterator.

This behavior seems unintuitive to me; and I could not find any documentation of this functionality. Due to this (I think) being a breaking change, it's probably not worth changing the take_while functionality, but documenting this is probably a good idea.

I tried this code:

fn main() {
    let a = [1, 2, 3, 4];
    let mut iter = a.into_iter();

    {
        let new_iter = iter.by_ref().take_while(|n| **n != 3);

        let mut back_to_vec: Vec<u32> = Vec::new();
        back_to_vec.extend(new_iter);
        println!("taken iter: {:?}", back_to_vec);
    }

    let mut back_to_vec: Vec<u32> = Vec::new();
    back_to_vec.extend(iter);
    println!("old iter: {:?}", back_to_vec);
}

I expected to see this output:

taken iter: [1, 2]
old iter: [3, 4]

Instead, this I saw this output:

taken iter: [1, 2]
old iter: [4]

Meta

rustc --version --verbose:

rustc 1.8.0-nightly (4b615854f 2016-01-26)
binary: rustc
commit-hash: 4b615854f00ba17ad704155e1d3196c17a6edb62
commit-date: 2016-01-26
host: x86_64-apple-darwin
release: 1.8.0-nightly

I believe this also occurs on stable (tested in play.rust-lang.org).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions