Shmoopy
Shmoopy

Reputation: 5534

Move ownership of a member from one struct to another?

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?

Upvotes: 10

Views: 4766

Answers (3)

Jason DeMorrow
Jason DeMorrow

Reputation: 579

Starting in Rust 1.40.0, you can use the mem::take function.

fn build_my_vector(&mut self) -> MyVector {
    MyVector { storage: take(self.storage) }
}

Upvotes: 1

red75prime
red75prime

Reputation: 3861

Yes. Pass ownership of MyVectorBuilder into MakeMyVector

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

Upvotes: 10

Matthieu M.
Matthieu M.

Reputation: 299810

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.

Upvotes: 5

Related Questions