Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move ownership of a member from one struct to another?

Tags:

rust

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?

like image 964
Shmoopy Avatar asked Jun 12 '17 08:06

Shmoopy


2 Answers

Yes. Pass ownership of MyVectorBuilder into MakeMyVector

fn make_my_vector(self) -> MyVector {
    MyVector { storage: self.storage }
}
like image 130
red75prime Avatar answered Sep 24 '22 00:09

red75prime


Is there a way to tell the compiler that MyVectorBuilder will not be used followning a call to BuildMyVector() so it will let me move the storage to MyVector ?

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.

like image 31
Matthieu M. Avatar answered Sep 22 '22 00:09

Matthieu M.