rust - "cannot move out of variable because it is borrowed"旋转变量时

标签 rust borrow-checker

我正在编写一个程序,该程序写入文件并时不时地轮换正在写入的文件。当我检查旋转文件时,我似乎无法更改文件,因为它是我的结构借用的。即使我删除 结构的实例,我似乎也无法重新获得文件的所有权来重命名它。 这是我的 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
    }
}

我知道我可以通过将文件创建移动到 FileStructnew 函数调用而不是使用中间变量 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.

因此,即使您调用 dropfile 仍将保持借用状态。

关于rust - "cannot move out of variable because it is borrowed"旋转变量时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34007692/

相关文章:

rust - 如何将编译期间命令行上提供的字符串编译成我的 Rust 二进制文件?

rust - 为什么在调用带有按值自取值的方法并同时调用一个方法的方法时,为什么要借用移动的值?

vector - 如何在迭代过程中改变向量的项?

struct - 如何向结构体的字段添加约束以进行实例化?

rust - 无法对array::Viewer进行数学运算

enums - 如何同时破坏枚举的字段和整体值?

rust - 由于类型不匹配错误,文本文件解析函数无法编译

rust - 如何使用普通引用创建一个简单的父子结构?

rust - 不可变值仍在移动

rust - 闭包可能比当前函数长寿