Skip to content

Commit

Permalink
Merge pull request #45 from llogiq/fix-38
Browse files Browse the repository at this point in the history
Add another example to the mem::replace idiom
  • Loading branch information
lambda-fairy authored Jan 3, 2017
2 parents 67870c8 + 964dd99 commit 3b37252
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions idioms/mem-replace.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,30 @@ fn a_to_b(e: &mut MyEnum) {
}
```

This also works with more variants:

```Rust
use std::mem;

enum MultiVariateEnum {
A { name: String },
B { name: String },
C,
D
}

fn swizzle(e: &mut MultiVariateEnum) {
use self::MultiVariateEnum::*;
*e = match *e {
// Ownership rules do not allow taking `name` by value, but we cannot
// take the value out of a mutable reference, unless we replace it:
A { ref mut name } => B { name: mem::replace(name, String::new()) },
B { ref mut name } => A { name: mem::replace(name, String::new()) },
C => D,
D => C
}
}
```

## Motivation

Expand Down

0 comments on commit 3b37252

Please sign in to comment.