I have 2 structs:
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 that MyVectorBuilder will not be used following a call to build_my_vector() so it will let me move the storage to MyVector?
Yes. Pass ownership of MyVectorBuilder into MakeMyVector
fn make_my_vector(self) -> MyVector {
MyVector { storage: self.storage }
}
Is there a way to tell the compiler that
MyVectorBuilderwill not be used followning a call toBuildMyVector()so it will let me move the storage toMyVector?
Yes, taking MyVectorBuilder by value:
fn build_my_vector(self) -> MyVector {
MyVector { storage: self.storage }
}
In general, I recommend that the build step of a builder takes its argument by value for precisely this reason.
If building twice is necessary, the builder can implement Clone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With