gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:31:50 30 4
gpt4 key购买 nike

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

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

最佳答案

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

关于rust - 包含对 Rust 中文件的引用的结构无法借用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55909798/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com