Skip to content

Commit 3b37252

Browse files
authored
Merge pull request #45 from llogiq/fix-38
Add another example to the mem::replace idiom
2 parents 67870c8 + 964dd99 commit 3b37252

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

idioms/mem-replace.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,30 @@ fn a_to_b(e: &mut MyEnum) {
3636
}
3737
```
3838

39+
This also works with more variants:
40+
41+
```Rust
42+
use std::mem;
43+
44+
enum MultiVariateEnum {
45+
A { name: String },
46+
B { name: String },
47+
C,
48+
D
49+
}
50+
51+
fn swizzle(e: &mut MultiVariateEnum) {
52+
use self::MultiVariateEnum::*;
53+
*e = match *e {
54+
// Ownership rules do not allow taking `name` by value, but we cannot
55+
// take the value out of a mutable reference, unless we replace it:
56+
A { ref mut name } => B { name: mem::replace(name, String::new()) },
57+
B { ref mut name } => A { name: mem::replace(name, String::new()) },
58+
C => D,
59+
D => C
60+
}
61+
}
62+
```
3963

4064
## Motivation
4165

0 commit comments

Comments
 (0)