Skip to content

Documentation of Iterator flatten() improvement #82687

Closed
@ralpha

Description

@ralpha

While linting my code I came across manual_flatten which was triggered in my code.

This suggests the change from:

for n in x {
    if let Some(n) = n {
        // something here
    }
}

Into:

for n in x.into_iter().flatten() {
    // something here
}

Both are valid code with same result.

But the rust docs on flatten() does not state that this is expected behavior. Yes, this is stated here.
But this was not strait forward (in my opinion) to find. It took me writing a whole bug report and looking a bunch of thing up to figure this out. (and I'm not even new to Rust anymore)

I would suggest adding some example code to make his explicit. Here is a suggestion:
(after the "Mapping and then flattening: <code>...</code>" section)

Flattening also works on other types like Option and Result:

let students_in_seats = vec![Some("Hasan"), Some("Sarah"), None, Some("Tim")];
let students_present: Vec<_> = students_in_seats.into_iter().flatten().collect();
assert_eq!(students_present, vec!["Hasan", "Sarah", "Tim"]);

(or something similar)

This makes both this behavior cleared, easier to find and exposes people to code like this so they are less surprised if clippy starts warning them.

It looks like this behavior might be more common in the future too.
rust-lang/rust-clippy#6061
rust-lang/rust-clippy#6676

Metadata

Metadata

Labels

A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsA-iteratorsArea: IteratorsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions