包含对Rust中文件引用的结构无法借用

时间:2019-04-29 19:39:20

标签: rust

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

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

1 个答案:

答案 0 :(得分:0)

正如@ 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();
}