0

I am trying to pass a new LineWriter into a statement from a struct to replace the current writer. In my main code chunk, I have this statement:

if let Some(ref mut tmp_writer) = self.the_writer {
    tmp_writer.write_all(/*...*/).unwrap();
}

I want to create a separate writer in a struct that can be returned to be used instead of the above tmp_writer. When calling it in a struct within my code I state:

use std::io::LineWriter;
use std::fs::File;

pub struct Test {
    final_writer: Option<LineWriter<File>>,
}

impl Test {
    pub fn new() -> Self {
        Test { final_writer: None }
    }

    pub fn return_writer(&mut self) -> LineWriter<File> {
        let fin_writer = self.final_writer.unwrap();
        return fin_writer;
    }
}

fn main() {}

When compiling, I get an error stating

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

How should I refactor my code so I can return a LineWriter<File> and not a &LineWriter<File>? If I do return it as a reference, how can I de-reference the writer without having another borrowed content issue?

Correct answer is:

pub fn return_writer(&mut self) -> LineWriter<File> {
    return self.final_writer.take().unwrap();
}

0 Answers0