Dereferencing boxed struct and moving its field causes it to be moved

前端 未结 2 528
心在旅途
心在旅途 2020-12-12 05:33

Dereferencing a boxed struct and moving its field causes it to be moved, but doing it in another way works just fine. I don\'t understand the difference between these two

2条回答
  •  长情又很酷
    2020-12-12 06:14

    You can only move out of a box once:

    struct S;
    
    fn main() {
        let x = Box::new(S);
        let val: S = *x;
        let val2: S = *x; // <-- use of moved value: `*x`
    }
    

    In the first function, you moved the value out of the box and assigned it to the node variable. This allows you to move different fields out of it. Even if one field is moved, other fields are still available. Equivalent to this:

    struct S1 {
        a: S2,
        b: S2,
    }
    struct S2;
    
    fn main() {
        let x = Box::new(S1 { a: S2, b: S2 });
    
        let tmp: S1 = *x;
        let a = tmp.a;
        let b = tmp.b;
    }
    

    In the second function, you move the value to the temporary (*boxed_node) and then move a field out of it. The temporary value is destroyed immediately after the end of the expression, along with its other fields. The box doesn't have the data anymore, and you don't have a variable to take the other field from. Equivalent to this:

    struct S1 {
        a: S2,
        b: S2,
    }
    struct S2;
    
    fn main() {
        let x = Box::new(S1 { a: S2, b: S2 });
    
        let tmp: S1 = *x;
        let a = tmp.a;
    
        let tmp: S1 = *x; // <-- use of moved value: `*x`
        let b = tmp.b;
    }
    

提交回复
热议问题