Skip to content

Commit fa88efb

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

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

text/0000-option-replace.md

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
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.
10+
11+
# Motivation
12+
[motivation]: #motivation
13+
14+
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.
15+
16+
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 ?
17+
18+
This is the symmetry of the already present `Option::take` method.
19+
20+
# Detailed design
21+
[design]: #detailed-design
22+
23+
This method will be added to the `core::option::Option` type implementation:
24+
25+
```rust
26+
use core::mem::replace;
27+
28+
impl<T> Option<T> {
29+
// ...
30+
31+
pub fn replace(&mut self, value: T) -> Option<T> {
32+
mem::replace(self, Some(value))
33+
}
34+
}
35+
```
36+
37+
# Drawbacks
38+
[drawbacks]: #drawbacks
39+
40+
It increases the size of the standard library by a tiny bit.
41+
42+
# Alternatives
43+
[alternatives]: #alternatives
44+
45+
- Don't use the `replace` name and use `give` instead in symmetry with the actual `take` method.
46+
- Use directly `mem::replace`.
47+
48+
# Unresolved questions
49+
[unresolved]: #unresolved-questions
50+
51+
None.

0 commit comments

Comments
 (0)