Moving out from a share reference

Hi,

I have a struct (simplifed) as given below.

pub struct manager1 {
        zip_writer:Option<SevenZWriter<File>>,
    }

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.

2 Likes

Yes, this worked, many thanks