Skip to content

Commit 82657ab

Browse files
committed
RFC: Add a replace method to Option
1 parent c892139 commit 82657ab

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

text/0000-option-replace.md

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
- Feature Name: `option-replace`
2+
- Start Date: 2017-01-16
3+
- RFC PR: (leave this empty)
4+
- Rust Issue: (leave this empty)
5+
6+
# Summary
7+
[summary]: #summary
8+
9+
The standard library provides the `Option::take` method that returns the optional inner value and leaves a `None` in place. This RFC proposes the addition of `Option::replace` to complete the previously cited method, this method replaces the actual value in the option by the value given in parameter, returning the old value if present, leaving a `Some` in its place without deinitializing either one.
10+
11+
# Motivation
12+
[motivation]: #motivation
13+
14+
Why are we doing this? What use cases does it support? What is the expected outcome?
15+
16+
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.
17+
18+
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 ?
19+
This is the same kind of method than the `take` one.
20+
21+
# Detailed design
22+
[design]: #detailed-design
23+
24+
This methid will be added to the `core::option::Option` type implementation:
25+
26+
```rust
27+
use core::mem::replace;
28+
29+
pub fn replace(&mut self, value: T) -> Option<T> {
30+
mem::replace(self, Some(value))
31+
}
32+
```
33+
34+
# Drawbacks
35+
[drawbacks]: #drawbacks
36+
37+
It increases the size of the standard library by a tiny bit.
38+
39+
# Alternatives
40+
[alternatives]: #alternatives
41+
42+
- Don't use the `replace` name and use `give` instead in symmetry with the actual `take` method.
43+
- Use directly `mem::replace`.
44+
45+
# Unresolved questions
46+
[unresolved]: #unresolved-questions
47+
48+
None.

0 commit comments

Comments
 (0)