[rust-dev] Avoiding partially moved values error when consuming a struct with multiple fields

Alex Crichton alex at crichton.co
Sun Jan 26 10:13:49 PST 2014


You'll want to do destructuring assignment here. This means that you
take ownership of all fields in parallel:

    fn into_test2(self) -> Test2 {
        let Test1 { a, b } = self;
        Test2 {
            c: a,
            d: b as f64
        }
    }

On Sun, Jan 26, 2014 at 9:32 AM, Vladimir Matveev
<dpx.infinity at gmail.com> wrote:
> Hi all,
>
> Consider this code:
>
> struct Test1 {
>     a: ~str,
>     b: f32,
> }
>
> struct Test2 {
>     c: ~str,
>     d: f64
> }
>
> impl Test1 {
>     fn into_test2(self) -> Test2 {
>         Test2 {
>             c: self.a,
>             d: self.b as f64
>         }
>     }
> }
>
>
> In into_test2() method I want to consume Test1 struct completely. But
> because ~str is not implicitly copyable, self.a is moved out of self,
> and on Test2.d field assignment I get the following error:
>
> main.rs:15:16: 15:21 error: use of partially moved value: `self`
> main.rs:15             d: self.b as f64
>                           ^~~~~
> main.rs:14:16: 14:22 note: `self.a` moved here because it has type
> `~str`, which is non-copyable (perhaps you meant to use clone()?)
> main.rs:14             c: self.a,
>                           ^~~~~~
>
> I know that I can, say, do self.a.clone() to avoid moving, but I don't
> want extra allocations. And it is also possible to reorder Test2
> fields assignments and it will work, but it won't if both fields are
> not copyable.
>
> So, the question is: how to correctly correctly move several pieces of
> data out from a struct without using clone()? Is it possible at all?
>
> Thanks,
> Vladimir.
> _______________________________________________
> Rust-dev mailing list
> Rust-dev at mozilla.org
> https://mail.mozilla.org/listinfo/rust-dev


More information about the Rust-dev mailing list