Skip to content

Misleading Iterator::filter_map example #46734

Closed
@dtolnay

Description

@dtolnay

This is the example currently given for Iterator::filter_map:

let a = ["1", "2", "lol"];

let mut iter = a.iter().filter_map(|s| s.parse().ok());

assert_eq!(iter.next(), Some(1));
assert_eq!(iter.next(), Some(2));
assert_eq!(iter.next(), None);

I find it a bit misleading that there are 3 array elements and 3 asserts that do not correspond in the obvious way. It is too easy to skim this and interpret it as:

let a = ["1", "2", "lol"];

let mut iter = a.iter().map(|s| s.parse().ok());

assert_eq!(iter.next().unwrap(), Some(1));
assert_eq!(iter.next().unwrap(), Some(2));
assert_eq!(iter.next().unwrap(), None);

I think using ["1", "lol", "3", "NaN", "5"] with four asserts would avoid the confusion.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and tools

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions