Skip to content

Add Option::take_if #98934

Closed
Closed
@kellerkindt

Description

@kellerkindt

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<u32>,
    // ...
}

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

Unresolved Questions

  • Provide both immutable and mutable retain methods (keeping it analogue to Vec)?
    Consensus seems to be to only implement retain take_if but with &mut T

Footnotes

  1. https://std-dev-guide.rust-lang.org/feature-lifecycle/stabilization.html

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-tracking-issueCategory: An issue tracking the progress of sth. like the implementation of an RFCT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.disposition-mergeThis issue / PR is in PFCP or FCP with a disposition to merge it.finished-final-comment-periodThe final comment period is finished for this PR / Issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions