Skip to content

Add give method to Option<T> #1416

@ghost

Description

Currently, Option<T> has the method take, which is implemented as replace(&mut self, None). To complement this method, I propose adding a give as well:

pub fn give(&mut self, val: T) -> Option<T> {
    ::std::mem::replace(self, Some(val))
}

#[test]
fn it_works() {
    let mut opt = None;
    assert_eq!(opt.give(5), None);
    assert_eq!(opt, Some(5));
    assert_eq!(opt.give(6), Some(5));
    assert_eq!(opt, Some(6));
}

This follows the same standard that HashMap, BTreeMap, and other collections use. Inserts a value into the option and returns the old value.

I feel like this is a common enough pattern to warrant a method from the standard library.

Metadata

Metadata

Assignees

No one assigned

    Labels

    T-libs-apiRelevant to the library API team, which will review and decide on the RFC.

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions