我正在编写一个程序,该程序写入文件并时不时地轮换正在写入的文件。当我检查旋转文件时,我似乎无法更改文件,因为它是我的结构借用的。即使我删除
结构的实例,我似乎也无法重新获得文件的所有权来重命名它。
这是我的 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
}
}
我知道我可以通过将文件创建移动到 FileStruct
的 new
函数调用而不是使用中间变量 file
,但我想知道为什么我强行删除所有应返回所有变量引用的变量的方法不起作用。
最佳答案
作为the std::mem::drop
documentation说,
While this does call the argument's implementation of
Drop
, it will not release any borrows, as borrows are based on lexical scope.
因此,即使您调用 drop
,file
仍将保持借用状态。
关于rust - "cannot move out of variable because it is borrowed"旋转变量时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007692/