Closed
Description
Tracking issue rust-lang/rust#98934
PR for impl rust-lang/rust#98935
Proposal
Add new Option::retain<F>(&mut self, predicate: F)
or similar to in-place replace self
with None
if it was Some(x)
before and the predicate evaluated to false on the value x
.
Problem statement
Writing if-let
statements in-between value assignments can be hideous and disturb the reading flow when updating a bunch of values in (nested) structs.
fn some_fn(values: &mut MyBigFlagStruct) {
values.x -= 7;
values.y += 42;
if let Some(z) = &value.z {
if *z < values.x * values.y {
values.z = None;
}
}
values.some_counter += 1;
if let Some(magic) = &values.magic {
if *magic != 42 {
values.magic = None;
}
}
}
Motivation, use-cases
This feature reduces the noise in the example from above:
fn some_fn(values: &mut MyBigFlagStruct) {
values.x -= 7;
values.y += 42;
values.z.retain(|z| *z >= values.x * values.y);
values.some_counter += 1;
values.magic.retain(|magic| *magic == 42);
}
Solution sketches
Alternative name
Maybe retain_if
?
values.magic.retain_if(|magic| *magic == 42);
Links and related work
What happens now?
This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.