Moving out from a share reference


I have a struct (simplifed) as given below.

pub struct manager1 {

When I am finished , I need to call the finish method, which I do as:

  let zip:SevenZWriter<File>=self.zip_writer.unwrap();
  let ResFinish=zip.finish();

For some reason SevenZWriter is defined as:

pub fn finish(self) -> Result<W>

so it consumes the self.zip_writer and compiler complains

 let zip:SevenZWriter<File>=self.zip_writer.unwrap();
    |                                        ^^^^^^^^^^^^^^^ -------- `self.zip_writer` moved due to this method call
    |                                        |
    |                                        help: consider calling `.as_ref()` or `.as_mut()` to borrow the type's contents
    |                                        move occurs because `self.zip_writer` has type `Option<SevenZWriter<std::fs::File>>`, which does not implement the `Copy` trait

Borrowing doesnt work here since, finish will consume it. :

  1. I dont need the zip object and happy to move it to the finish method.
  2. I was thinking of setting self.zip_writer to None.

What is the best solution here?

You probably want take:

Takes the value out of the option, leaving a None in its place.

You will need a unique (&mut) reference to self, not a shared (&) reference, because you are mutating it by replacing the contents of self.zip_writer with None.


Yes, this worked, many thanks

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.