-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Closed
Labels
T-libs-apiRelevant to the library API team, which will review and decide on the RFC.Relevant to the library API team, which will review and decide on the RFC.
Description
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 })
eddyb, Mark-Simulacrum, JaniM, maltek, earl and 27 moreLukasKalbertodt and dnrusakov
Metadata
Metadata
Assignees
Labels
T-libs-apiRelevant to the library API team, which will review and decide on the RFC.Relevant to the library API team, which will review and decide on the RFC.