This should not compile?

Should this compile, my initial expectation was that it would not…..

let v = Box::new(42);
println!("{:p}", v);       // Print the address of the Box
println!("{:#?}", *v);     // Print the value inside the Box

let y = *v;                 // Dereference the Box, move the value into y
println!("{}", v);          // Attempting to use v after moving its content (compiles but won't print what you expect)
println!("{}", y);          // Print the value stored in variable y

In Rust, moving a value out of a Box or any other owned container is allowed, but it doesn’t invalidate the original variable (v in this case). The variable v is still in scope, and you can continue using it. However, when you print v after moving its content into y, it won’t display what you might expect. The reason is that the Debug implementation for Box prints the address, not the content.

So, while the code does compile, the last println!("{}", v); line may not provide the expected result in terms of printing the value inside the Box. If you want to access the content of the Box after moving, you should create a new Box or use the original Box again.

    let v = Box::new(42);
    println!("{:p}", v);
    println!("{:#?}", *v);
    let y = *v;

    println!("{}", v);
    println!("{:#?}", v);

    let y = v; // Ownership of the Box is transferred to y

    println!("{}", *v); // This line would result in a compilation error
    println!("{}", *y); // This line is valid, as y now owns the Box

In the example above, after the line let y = v;, the ownership of the Box is moved from v to y. Consequently, using *v would result in a compilation error because v no longer owns the Box. However, you can continue using the variable y to access the value inside the Box.

Line 4 just sets y to the VALUE at the address of v

The “*” makes the difference…it fetches the value rather than the address.

println! macro uses the std::fmt::Display trait to format and print values.

Instead of explicitly writing println!("{}", *v); to dereference the Box, you can use println!("{}", v);, and Rust will handle the necessary dereferencing behind the scenes when the Display trait is implemented for the type inside the Box.

Previous article

Musl – static linking