Moving value from Box

How this code work? How value moved from Box? I did not find a method to do this manually.

struct A{
impl A{
    fn test(self){
        println!("Moved, {}",self.x);
impl Drop for A{
    fn drop(&mut self){
fn main(){
    let a=Box::new(A{x:3});

What do you mean by "manually"?

Doing a.x in main() would also get you 3 (albeit that "move" would be a copy since u32: Copy)

Could you show us the code that doesn't work which you expected to work? Without that I really can't tell what's puzzling about this working code.

I'm trying to understand the mechanism of movement from the Box. No compilation issues

Indeed, for the compiler, a Box is just a structure that does not contain directly A

Well, "mechanism" is still pretty vague. At the Rust language level, it "just" dereferences the pointer inside the Box, and considers the Box to be moved-from/unusuable from then on. But I'm guessing that's not what you're after?

If you're asking why a.x is allowed to move out of x when a is a Box, but not for any other "smart pointer" types, that's a piece of Box-specific magic that is not otherwise exposed by the Rust language. There's a long history of proposals to de-magic it by introducing a DerefMove trait or something.

1 Like
1 Like