rust - 包含对 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
解决方案
正如@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();
}
推荐阅读
- r - 如何将生成的热图导出为 R 中的 8 位/16 位 tiff 图像,以便在 ImageJ/Fiji 中进行分析?
- websocket - Micronaut Websocket 连接每 5 分钟超时一次
- python - node-red 中的 Python 函数 - Windows 系统上的问题
- rust - 如何在通过 C++ 创建的 Rust 代码中保存 Rust 对象?
- validation - 如何将全局键 _keyForm 放在我的 TextFormField 中,因为它由不同的小部件分隔
- yocto - 不同的已经可用的 yocto 变量?
- java - Spring MVC Controller 引用属性文件中的字符串
- javascript - Javascript过滤字符串和布尔数组对象和重复值
- groovy - Spock UnitTest,调用太少,但“不匹配的调用”列表中的调用完全相同
- arrays - 快速从字典数组中创建字符串数组