Move a member's ownership from one structure to another?
I have 2 structures:
struct MyVector {
storage: Vec<u32>,
}
struct MyVectorBuilder {
storage: Vec<u32>,
}
impl MyVectorBuilder {
fn new() -> MyVectorBuilder {
MyVectorBuilder { storage: Vec::new() }
}
fn build_my_vector(&mut self) -> MyVector {
// Doesn't compile: ^^^^ cannot move out of borrowed content
MyVector { storage: self.storage }
}
}
Is there a way to tell the compiler what MyVectorBuilder
will not be used after the call build_my_vector()
, so it will allow me to move storage
to MyVector
?
source to share
Is there a way to tell the compiler what
MyVectorBuilder
will not be used after the call is invokedBuildMyVector()
, so it will allow me to move the store toMyVector
?
Yes, taking MyVectorBuilder
by value:
fn build_my_vector(self) -> MyVector {
MyVector { storage: self.storage }
}
In general, I recommend that the build
builder step takes an argument by value for this very reason.
If the building is required twice, the builder can implement Clone
.
source to share