Skip to content

Add filter to Option #1485

Closed
Closed
@zorgiepoo

Description

@zorgiepoo

Coming from Scala, I miss not having a filter method on Option. I believe the function signature would be:

fn filter<P: FnOnce(&T) -> bool>(self, predicate: P) -> Self

Last use case I was using it for:

let valid_line = |x: &str| -> bool { x.trim().len() > 0 && !x.starts_with("#") };
let input_line: Option<String> = ...; // read from somewhere
let line = input_line.filter(|x| valid_line(&x));

There may be other use cases since we live with strings and collections, and sometimes we want to not consider "close" to zero length. The idea would be to filter out "undesired" options.

Workarounds: turn the option into an iterator and call next(), or use and_then, or write your own trait implementation. If this feature is desired, I'd be happy to send a pull request. Using and_then is probably how I'd implement it:

self.and_then(|x| if predicate(&x) { Some(x) } else { None })

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions