|
| 1 | +## Update text using `swap`, `take`, and `replace` |
| 2 | + |
| 3 | +[![std-badge]][std] [![cat-rust-patterns-badge]][cat-rust-patterns] |
| 4 | + |
| 5 | +Uses [`mem::swap`], [`mem::take`], and [`mem::replace`] to move owned String values between document fields without cloning. |
| 6 | +[`mem::swap`] exchanges the drafts of two documents, [`mem::take`] moves a draft out for publishing while leaving an empty String behind, |
| 7 | +and [`mem::replace`] installs the new published text while returning the previous version. |
| 8 | + |
| 9 | +```rust,edition2021 |
| 10 | +use std::mem::{replace, swap, take}; |
| 11 | +
|
| 12 | +struct Document { |
| 13 | + name: &'static str, |
| 14 | + draft: String, |
| 15 | + published: String, |
| 16 | +} |
| 17 | +
|
| 18 | +impl Document { |
| 19 | + fn publish(&mut self) -> String { |
| 20 | + let next_version = take(&mut self.draft); |
| 21 | + replace(&mut self.published, next_version) |
| 22 | + } |
| 23 | +} |
| 24 | +
|
| 25 | +fn main() { |
| 26 | + let mut guide = Document { |
| 27 | + name: "Guide", |
| 28 | + draft: "Guide Version 2".to_string(), |
| 29 | + published: "Guide Version 1".to_string(), |
| 30 | + }; |
| 31 | +
|
| 32 | + let mut release_notes = Document { |
| 33 | + name: "Release notes", |
| 34 | + draft: "Release notes for version 2".to_string(), |
| 35 | + published: "Release notes for version 1".to_string(), |
| 36 | + }; |
| 37 | +
|
| 38 | + swap(&mut guide.draft, &mut release_notes.draft); |
| 39 | +
|
| 40 | + println!("Swapped:"); |
| 41 | + println!("{} draft: {}", guide.name, guide.draft); |
| 42 | + println!("{} draft: {}", release_notes.name, release_notes.draft); |
| 43 | +
|
| 44 | + let previous_version = guide.publish(); |
| 45 | +
|
| 46 | + assert!(guide.draft.is_empty()); |
| 47 | + assert_eq!(guide.published, "Release notes for version 2"); |
| 48 | + assert_eq!(previous_version, "Guide Version 1"); |
| 49 | +} |
| 50 | +``` |
| 51 | + |
| 52 | +[`mem::swap`]: https://doc.rust-lang.org/std/mem/fn.swap.html |
| 53 | +[`mem::replace`]: https://doc.rust-lang.org/std/mem/fn.replace.html |
| 54 | +[`mem::take`]: https://doc.rust-lang.org/std/mem/fn.take.html |
| 55 | + |
0 commit comments