Joey
Joey

Reputation: 225

why the value in Box can be moved out?

I wrote a function to test the deference of Box in Rust:

    struct S;
    fn f1() {
      // test1
      let s1 : Box<S> = Box::new(S);
      let s2 : S = *s1;   // The S in s1 is moved to s2;

      // test2
      let mut s3 : Box<S> = Box::new(S);
      // let s4 : S = *DerefMut::deref_mut(&mut s3); //compile error: cannot move out of a mutable reference.

      // test3
      let mut s5 : &mut S = &mut S;
      //  let s6 :S = *s5;   //compile error: cannot move out of a mutable reference.
        
    }
 

I know a value cannot be moved out of a reference (like test2 and test3), but why the value in Box can be moved out (like test1). I thought test1 and test2 are equal.

Upvotes: 1

Views: 70

Answers (1)

Sebastian Redl
Sebastian Redl

Reputation: 72142

Because Box is known to the compiler as a very special type. It has a special exception to the usual dereference rules to make this possible.

You can find a more detailed explanation in this blog post: https://manishearth.github.io/blog/2017/01/10/rust-tidbits-box-is-special/

Upvotes: 2

Related Questions