我有一个函数,应该读取一个文件并返回它的内容。
fn read (file_name: &str) -> &str {
let mut f = File::open(file_name)
.expect(&format!("file not found: {}", file_name));
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect(&format!("cannot read file {}", file_name));
return &contents;
}
但是我收到此错误:
--> srcmain.rs:20:13
|
20 | return &contents;
| ^^^^^^^^ borrowed value does not live long enough
21 | }
| - borrowed value only lives until here
|
我做错了什么?
我对这里发生的事情的想法是这样的:
let mut f = File::open(file_name).expect(....);
- 这需要文件的句柄,并告诉操作系统我们要用它做一些事情。let mut contents = String::new();
- 这会在堆上创建一个类似矢量的数据结构,以便存储我们将要从文件中读取的数据。f.read_to_string(&mut contents).expect(...);
- 这会将文件读入contents
空间。return &contents;
- 这将返回指向存储文件数据的向量的指针。
为什么我无法返回所需的指针?
如何关闭我的文件(f
变量(?我认为在变量超出范围后 rust 会为我关闭它,但是如果我需要在此之前关闭它怎么办?
当文件句柄的变量超出范围时,文件句柄会自动关闭是正确的;同样的情况也会发生在contents
,但是 - 它将在函数结束时被销毁,除非您决定将其作为拥有的String
返回。在 Rust 中,函数不能返回对在其中创建的对象的引用,只能返回作为参数传递给它们的对象的引用。
您可以按如下方式修复函数:
fn read(file_name: &str) -> String {
let mut f = File::open(file_name)
.expect(&format!("file not found: {}", file_name));
let mut contents = String::new();
f.read_to_string(&mut contents)
.expect(&format!("cannot read file {}", file_name));
contents
}
或者,可以将contents
作为对read
函数的可变引用传递:
fn read(file_name: &str, contents: &mut String) { ... }