I keep getting the compiler error: "move occurs because self.sth has type S1, which does not implement the Copy trait":
struct S1 {field1: String, field2: i32}
struct S2 {sth: S1}
struct Builder {sth: S1}
impl Builder {
fn new(sth: S1) -> Builder {Builder{sth}}
fn build(&self) -> S2 {S2{sth: self.sth}}
}
fn main() {
let s1 = S1{field1: "asd".to_owned(), field2: 32};
let _ = Builder::new(s1).build();
}
Compiler error:
error[E0507]: cannot move out of `self.sth` which is behind a shared reference
--> src/main.rs:7:36
|
7 | fn build(&self) -> S2 {S2{sth: self.sth}}
| ^^^^^^^^ move occurs because `self.sth` has type `S1`, which does not implement the `Copy` trait
What I actually want to do is just move S1 through the Builder::new to it's final destination - in S2 without copying it all the time (my understanding is that Copy trait does that).
I could use a reference in S2 but the field is long lived and I'd prefer to store there it's value. Currently the way with references would be to have all the arguments defined first before calling the builder and then consuming their references. So how do I consume a struct without copying it all the time?