Use std::mem::replace to temporarily swap a value out of a field, allowing you to borrow the original struct while working with the replaced value.
use std::mem;
struct Data {
value: String,
}
fn process(data: &mut Data) {
// Replace the value with a temporary empty string
let old_value = mem::replace(&mut data.value, String::new());
// Now we can use `old_value` and `data` independently
println!("Old: {}", old_value);
println!("Data: {:?}", data);
// Restore the value if needed
data.value = old_value;
}
Use std::mem::swap when you need to exchange values between two variables or fields without allocating a temporary placeholder.
use std::mem;
fn swap_values(a: &mut String, b: &mut String) {
mem::swap(a, b);
}
replace is ideal for extracting a value from a struct to satisfy borrow checker constraints, while swap is best for exchanging two existing values directly.