gpt4 book ai didi

rust - 用 Rust 读取文件 - 借用的值只存在到这里

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

我有一个函数应该读取一个文件并返回它的内容。

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;
}

但是我得到这个错误:

  --> src\main.rs:20:13
|
20 | return &contents;
| ^^^^^^^^ borrowed value does not live long enough
21 | }
| - borrowed value only lives until here
|

我做错了什么?

我对这里发生的事情的想法是:

  1. let mut f = File::open(file_name).expect(....); - 这获取一个文件的句柄并告诉操作系统我们想要做什么

  2. let mut contents = String::new(); - 这会在堆上创建一个类似向量的数据结构,以存储我们即将从文件。

  3. f.read_to_string(&mut contents).expect(...); - 这会将文件读入 contents 空间。

  4. 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) { ... }

关于rust - 用 Rust 读取文件 - 借用的值只存在到这里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51179353/

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