首页 > 解决方案 > 包含对 Rust 中文件的引用的结构无法借用

问题描述

不确定我在这里缺少什么,声明了生命周期,因此结构应该使用路径来创建文件并返回一个带有可变文件引用的结构,以便我以后能够调用“写入”包装器......

use std::path::Path;
use std::fs::File;
// use std::io::Write;

#[derive(Debug)]
pub struct Foo<'a> {
    file: &'a mut File,
}

impl<'a> Foo<'a> {
    pub fn new(path: &'a Path) -> Result<Self, std::io::Error> {
        let mut f: &'a File = &File::create(path)?;

        Ok(Self { file: &mut f })
    }

    //pub fn write(&self, b: [u8]) {
    //    self.file.write(b);
    //}
}

错误:

   | impl<'a> Foo<'a> {
   |      -- lifetime `'a` defined here
11 |     pub fn new(path: &'a Path) -> Result<Self, std::io::Error> {
12 |         let mut f: &'a File = &File::create(path)?;
   |                    --------    ^^^^^^^^^^^^^^^^^^^ creates a temporary which is freed while still in use
   |                    |
   |                    type annotation requires that borrow lasts for `'a`
...
15 |     }
   |     - temporary value is freed at the end of this statement

标签: rust

解决方案


正如@E_net4 提到的,我不想要一个可变的引用,但我想拥有这个值。我基本上可以只拥有文件并在尝试写入文件时将整个结构处理为可变的,而不是尝试使用生命周期!

use std::path::{ PathBuf };
use std::fs::File;
use std::io::Write;
use std::env;


#[derive(Debug)]
pub struct Foo {
    file:  File,
}

impl Foo {
    pub fn new(path: PathBuf) -> Self {
        Self { 
          file: File::create(path).unwrap(),
        }
    }

    pub fn write(&mut self, b: &[u8]) -> Result<usize, std::io::Error> {
        self.file.write(b)
    }
}

fn main() {
    let mut tmp_dir = env::temp_dir();
    tmp_dir.push("foo23");
    let mut f = Foo::new(tmp_dir);

    f.write(b"test2").unwrap();
}

推荐阅读