ownership

Rust Moving out of a Box

Box supports moving out its owned payload when the box itself is owned. Unlike moving from a borrowed reference, this can transfer a non-Copy value without cloning. The source box cannot then be used as if it were intact. Expected output (not executed): draft ready Why: Ownership of the String passes to text. Common mistake: Assuming every Deref implementation permits moving out of the target.

Formal Syntax & Structure

rust syntaxrust
let value = *boxed;

Working Example

Example Snippetrust
fn main() {    let boxed = Box::new(String::from("draft"));    let mut text = *boxed;    text.push_str(" ready");    println!("{text}");}
Rust Reference