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

Vladimir Matveev dpx.infinity at gmail.com
Sun Jan 26 09:32:11 PST 2014


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.


More information about the Rust-dev mailing list