Skip to content

Can't directly destructure boxed values #33550

Closed
@jdm

Description

@jdm

This compiles:

struct Foo {
  s: String,
  s2: String,
}

impl Foo {
    fn bar(self: Box<Self>) {
        let f = *self;
        let _a = f.s;
        let _b = f.s2;
    }
}

fn main() {
    let f = Foo { s: "hi".to_owned(), s2: "bye".to_owned() };
    Box::new(f).bar();
}

This does not:

struct Foo {
  s: String,
  s2: String,
}

impl Foo {
    fn bar(self: Box<Self>) {
        let Foo { s, s2 } = *self;
    }
}

fn main() {
    let f = Foo { s: "hi".to_owned(), s2: "bye".to_owned() };
    Box::new(f).bar();
}

Due to this error:

<anon>:8:22: 8:24 error: use of moved value: `self` [E0382]
<anon>:8         let Foo { s, s2 } = *self;
                              ^~
<anon>:8:22: 8:24 help: see the detailed explanation for E0382
<anon>:8:19: 8:20 note: `self` moved here (through moving `self.s`) because it has type `collections::string::String`, which is moved by default
<anon>:8         let Foo { s, s2 } = *self;
                           ^
<anon>:8:19: 8:20 help: if you would like to borrow the value instead, use a `ref` binding as shown:
<anon>:          let Foo { ref s, s2 } = *self;
error: aborting due to previous error
playpen: application terminated with error code 101

I don't understand why one form is legal and the other is not, and the error message does not make it clear to me.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions