mem::take
and mem::replace
are both used to manipulate ownership and values, but they work slightly differently.
mem::take
: This function takes ownership of a value and replaces it with a default value of the same type. The original value is returned. It’s commonly used when you want to replace a value with a default while getting the original value in return. You’ll see an example in a bit.mem::replace
: This function also takes ownership of a value and replaces it with a new value. However, the new value can be of a different type than the original value. The original value is returned as well. This is often used when you want to replace a value with a different value of a possibly different type.
Here’s a simple comparison:
mem::take example:
use std::mem;
fn main() {
let mut value = String::from("Hello");
let taken_value = mem::take(&mut value);
println!("Original value: {}", taken_value); // Prints "Original value: Hello"
println!("New value: {}", value); // Prints "New value: "
}
mem::replace example:
use std::mem;
fn main() {
let mut value = String::from("Hello");
let replaced_value = mem::replace(&mut value, "World".to_string());
println!("Original value: {}", replaced_value); // Prints "Original value: Hello"
println!("New value: {}", value); // Prints "New value: World"
}
In summary, mem::take
replaces the original value with a default value and gives you the original value back, while mem::replace
lets you replace the value with a new value and also gives you the original value. The choice between them depends on whether you want to replace with a default or a different value, and whether you need the original value after the replacement.