Add Option::take_if (original) (raw)
Feature gate:#![feature(option_take_if)]
This is a tracking issue for adding Option::retain_if similar to Option::take but requires an additional predicate.
It takes() the value if the predicate evaluates to true. If the predicate evaluates to false, the value of the Option remains Some(...). The predicate (Fn(&mut T) -> bool) also has the chance to modify the value.
struct MyStruct { pub some_value: Option, // ... }
fn main() { let mut my_struct: MyStruct = out_of_thin_air();
do_something_before(&my_struct);
// on non-copy values, this would require a multiple line long match or if-let instead
my_struct.some_value.take_if(|x| *x == 42);
// also allows this
if let Some(prev) = my_struct.some_value.take_if(|x| *x != 42) {
// do something with the previous value
}
do_something_after(&mut my_struct);
pass_on(my_struct);}
Steps / History
- ACP: Add Option::retain libs-team#70
- Implementation: Implement Option::take_if #98935
- Final comment period (FCP)1
- Stabilization PR
Unresolved Questions
Provide both immutable and mutable retain methods (keeping it analogue toVec)?
Consensus seems to be to only implementretaintake_ifbut with&mut T