1

I would like to move the value of one struct's field to another struct like this:

struct MyStruct {
    value1: Option<Vec<usize>>,
    value2: i32,
    // ...,
}

impl MyStruct {
    pub fn child(&mut self, value2: i32) -> MyStruct {
        let mut value1 = self.value1.unwrap();

        // Do some stuff..

        MyStruct {
            value1: Some(value1),
            value2: value2,
        }
    }
}

fn main() {
    let mut first = MyStruct {
        // Building the first structure
        value1: Some((0..10).map(|_| 0).collect()),
        value2: 0,
    };

    // Using it

    let second = first.child(1);
}

I get an error:

error[E0507]: cannot move out of borrowed content
 --> src/main.rs:9:26
  |
9 |         let mut value1 = self.value1.unwrap();
  |                          ^^^^ cannot move out of borrowed content

How can I tell Rust to move value1 from the first instance to the second, leaving value1 of first equal to None?

Later in my code I need to go back to potentially all the instances I used, reading other values but not the vector.

I used to do a copy of the field but since I'm exploring a graph that is really huge, memory can't take it and it's not very efficient.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

1

Thanks to E_net4 I found an easy way of doing it :

pub fn child(&mut self, value2: i32) -> MyStruct {
    MyStruct {
        value1: self.value1.take(),
        value2: value2,
    }
}

Here, value1: self.value1.take() moves the value1 content from self to the new structure, leaving None in self.value1.