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

?

+3


source to share


2 answers


Yes. Transfer ownership MyVectorBuilder

toMakeMyVector



fn make_my_vector(self) -> MyVector {
    MyVector { storage: self.storage }
}

      

+5


source


Is there a way to tell the compiler what MyVectorBuilder

will not be used after the call is invoked BuildMyVector()

, so it will allow me to move the store to MyVector

?

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

.

+5


source







All Articles