Skip to content

Add Option::retain #70

Closed
Closed
@kellerkindt

Description

@kellerkindt

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions