What happens when I write let unboxed=*some_box;?

I'm thinking about how to unbox a value from a Box and I find that I can write:

struct Ts{
v:i32
}

let some_box=Box::new(Ts{v:3});
let unboxed=*some_box;

then I confirmed that some_box has been consumed through trying to access some_box.v (which of course failed).

What I'm curious about is that what happened at *some_box?

Why some_box can be derefed by *? I found that it is not simply because it impled Deref trait, as I tried to write
let unboxed=*(some_box.deref()), but failed.

When you do *some_box like that you are actually moving the thing out of the box and into a new variable.

The Box type is kinda special in that the compiler knows how to dereference a Box<T>. If you look at the Deref impl in the standard library you'll see that dereferencing a box is actually implemented in terms of itself (&**self), which would normally result in infinite recursion. Instead Deref for Box<T> is built straight into the compiler.

I believe Box being a special type built into the compiler is a side-effect of the pre-1.0 days, although I wasn't using Rust back and don't hack on the compiler internals, so don't quote me on that.

1 Like

Thanks, and I find following thing:

, which agrees with what you said.

1 Like

As I understand it, it's exactly because of the situation in this thread. There have been nebulous thoughts of a new trait like DerefMove to let user types (and Box, which would no longer be special) be able to do this too, but the details haven't been worked out yet.