Mem Take And Replace Owned Values
Move owned values out of mutable places with mem::take and mem::replace: the old value is handed over and a default or new value takes its slot without clone.
Code
use std::mem;
fn drain_queue(q: &mut String) -> String {
// take:移出当前值、留下 Default::default()(空串),借用立即恢复可用
mem::take(q)
}
fn main() {
let mut queue = String::from("job-a;job-b;job-c");
let drained = drain_queue(&mut queue);
println!("drained: {drained}");
println!("queue after take: '{}'", queue);
// replace:写入新值的同时拿回旧值,一次移动完成
let old = mem::replace(&mut queue, String::from("job-d"));
println!("swapped {old} out, queue now {queue}");
// swap:两个同类型值互换所有权
let mut a = String::from("primary");
let mut b = String::from("standby");
mem::swap(&mut a, &mut b);
println!("a={a} b={b}");
}What the code does
Structurally, expect the functions drain_queue and main and nothing else.
Using it
The main signature reads fn drain_queue(q: &mut String) -> String
The demo output is labeled (drained:, queue after take: ', swapped), so every printed line maps back to its originating operation.
There are 1 call inside main — drain_queue — executed top to bottom.
Key statements
fn drain_queue(q: &mut String) -> String {
// take:移出当前值、留下 Default::default()(空串),借用立即恢复可用
mem::take(q)
}
Interactive Tools for This Topic
FAQ
- What does Mem Take And Replace Owned Values print when run?
- No setup needed: run the file and look for labeled lines like `drained:`, `queue after take: '`, `swapped` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.