Skip to content

Commit

Permalink
RFC: Add a replace method to Option
Browse files Browse the repository at this point in the history
  • Loading branch information
Kerollmops committed Jan 22, 2018
1 parent c892139 commit fa88efb
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions text/0000-option-replace.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
- Feature Name: `option-replace`
- Start Date: 2017-01-16
- RFC PR: (leave this empty)
- Rust Issue: (leave this empty)

# Summary
[summary]: #summary

This RFC proposes the addition of `Option::replace` to complete the `Option::take` method, it replaces the actual value in the option by `Some` with the value given in parameter, returning the old value if present, without deinitializing either one.

# Motivation
[motivation]: #motivation

You can see the `Option` as a container and other containers already have this kind of method to change a value in-place like the [HashMap::replace](https://doc.rust-lang.org/std/collections/struct.HashSet.html#method.replace) method.

How do you replace a value inside an `Option`, you can use `mem::replace` but it can be really unconvenient to import the `mem` module just for that. Why not adding a useful method to do that ?

This is the symmetry of the already present `Option::take` method.

# Detailed design
[design]: #detailed-design

This method will be added to the `core::option::Option` type implementation:

```rust
use core::mem::replace;

impl<T> Option<T> {
// ...

pub fn replace(&mut self, value: T) -> Option<T> {
mem::replace(self, Some(value))
}
}
```

# Drawbacks
[drawbacks]: #drawbacks

It increases the size of the standard library by a tiny bit.

# Alternatives
[alternatives]: #alternatives

- Don't use the `replace` name and use `give` instead in symmetry with the actual `take` method.
- Use directly `mem::replace`.

# Unresolved questions
[unresolved]: #unresolved-questions

None.

0 comments on commit fa88efb

Please sign in to comment.