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

问题描述 投票:0回答:1

不知道我在这里缺少什么,生命周期被声明,因此结构应该使用路径来创建文件并返回带有可变文件引用的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
rust
1个回答
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();
}
© www.soinside.com 2019 - 2024. All rights reserved.