I write a program that writes to a file and occasionally rotates the file that it writes. When I check to rotate the file, I cannot change the file because it is borrowed from my structure. Even if I drop instance of the structure, I cannot regain ownership of the file to rename it. Here is my example :
use std::fs::File; use std::io::{Write}; use std::mem::{drop}; pub struct FileStruct<W: Write> { pub writer: Option<W>, } impl <W: Write> FileStruct<W> { pub fn new(writer: W) -> FileStruct<W> { FileStruct { writer: Some(writer), } } } fn main() { let mut file = File::create("tmp.txt").unwrap(); let mut tmp = FileStruct::new(&mut file); loop { if true { //will be time based if check drop(tmp); drop(file); file = File::create("tmp2.txt").unwrap(); tmp = FileStruct::new(&mut file); } // write to file } }
I know that I can make this work by moving the file creation to a call to the new function of the FileStruct function instead of the intermediate variable file , but I would like to know why this method, where I force drop all variables, where all variable references should be returned, are not work.
source share