mem swap Exchanges Two Places At Once
Exchange two owned values in one operation with std::mem::swap, which moves contents through pointers and never clones payloads.
Code
use std::mem;
fn main() {
let mut left = String::from("primary");
let mut right = String::from("standby");
// swap:两个 &mut 位置整体互换内容,零克隆、零分配
mem::swap(&mut left, &mut right);
println!("left: {left}, right: {right}");
// 同一容器内:以自身某两个元素为操作数也成立
let mut queue = vec![String::from("head"), String::from("mid"), String::from("tail")];
mem::swap(&mut queue[0], &mut queue[2]);
println!("queue: {queue:?}");
// swap 配合引用,可以把交换封装成小函数而不转移所有权
fn promote(active: &mut String, candidates: &mut Vec<String>) {
if let Some(candidate) = candidates.last() {
let taken = String::from(candidate.as_str());
mem::swap(active, &mut { taken });
}
}
let mut service = String::from("old-node");
let mut pool = vec![String::from("new-node")];
promote(&mut service, &mut pool);
println!("service: {service}");
// 对照 replace:swap 要求两个已初始化的位置,replace 只要求一个
let previous = mem::replace(&mut pool[0], String::from("pool-slot"));
println!("replaced in: {previous}");
}How it works
The part worth importing is the functions main and promote — everything else is wiring.
Watch out for
- No package manager runs in the flow — every call lands on a built-in API.
Putting it to use
Signature: fn main()
Look for the left:, queue:, service: prefixes as the file executes; they connect every printed line to the step behind it.
main sequences promote; executing the file runs that flow once.
Core lines under the microscope
fn promote(active: &mut String, candidates: &mut Vec<String>) {
if let Some(candidate) = candidates.last() {
let taken = String::from(candidate.as_str());
mem::swap(active, &mut { taken });
}
}
Interactive Tools for This Topic
FAQ
- What does mem swap Exchanges Two Places At Once print when run?
- Running the file directly is enough — expect labeled output lines such as `left:`, `queue:`, `service:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.