std-function

Rust mem::take(): move out and reset

take replaces a value through a mutable reference with its type’s Default value and returns the previous owner. It is useful for draining a buffer while keeping its storage slot initialized. Default is type-specific and is not always an empty value. Expected output (not executed): Sent: Order 7 Empty: true Why: The old String is returned, while pending now holds the default empty String. Common mistake: Assuming take clones the old value or works for every type without a Default implementation.

Formal Syntax & Structure

rust syntaxrust
pub fn take<T: Default>(dest: &mut T) -> T

Working Example

Example Snippetrust
use std::mem;fn main() {    let mut pending = String::from("Order 7");    let sent = mem::take(&mut pending);    println!("Sent: {sent}");    println!("Empty: {}", pending.is_empty());}
Rust Reference