How does Box transfer ownership

Box<T> transfers ownership by moving the heap pointer to a new variable, invalidating the original owner.

In Rust, Box<T> transfers ownership by moving the pointer to the heap data, not the data itself. When you assign a Box<T> to a new variable, the original variable is invalidated, and the new variable becomes the sole owner of the heap-allocated value.

fn main() {
    let b1 = Box::new(5);
    let b2 = b1; // Ownership of the Box moves to b2
    // println!("{b1}"); // Error: b1 is moved
    println!("{b2}"); // OK: b2 owns the value
}