gpt4 book ai didi

rust - 如何从文件中读取字符串,将其拆分,然后在一条语句中创建Vec <&str>?

转载 作者:行者123 更新时间:2023-12-03 11:44:15 24 4
gpt4 key购买 nike

我需要有关如何将作为字符串的文件输入转换为向量的帮助。
我试过了

let content = fs::read_to_string(file_path).expect("Failed to read input");
let content: Vec<&str> = content.split("\n").collect();
这行得通,但我想将其转换为一条语句。就像是
let content: Vec<&str> = fs::read_to_string(file_path)
.expect("Failed to read input")
.split("\n")
.collect();
我尝试使用
let content: Vec<&str> = match fs::read_to_string(file_path) {
Ok(value) => value.split("\n").collect(),
Err(err) => {
println!("Error Unable to read the file {}", err);
return ();
}
};

let content: Vec<&str> = match fs::read_to_string(file_path) {
Ok(value) => value,
Err(err) => {
println!("Error Unable to read the file {}", err);
return ();
}
}
.split("\n")
.collect();
编译器说,借入的值没有足够长的生命周期(第一个),而在使用中却释放了值(第二个)(借入,范围和所有权存在问题)。
error[E0716]: temporary value dropped while borrowed
--> src/lib.rs:4:26
|
4 | let content: Vec<&str> = fs::read_to_string("")
| __________________________^
5 | | .expect("Failed to read input")
| |___________________________________^ creates a temporary which is freed while still in use
6 | .split("\n")
7 | .collect();
| - temporary value is freed at the end of this statement
8 |
9 | dbg!(content);
| ------- borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
对于如何修复它们,我仍然缺乏足够的了解。

最佳答案

用一个表达式不可能做到这一点。就像您已经使用的那样,并按照编译器告诉您的那样,使用两个带有let的表达式。

问题在于split会生成引用临时&str的字符串切片(String)。该String在语句的末尾被释放,从而使引用无效。 Rust阻止您引入内存不安全性:

fs::read_to_string(file_path)        // Creates a String
.expect("Failed to read input")
.split("\n") // Takes references into the String
.collect(); // String is dropped, invalidating references
如果您不需要 Vec<&str>,则可以使用 Vec<String>:
fs::read_to_string(file_path)
.expect("Failed to read input")
.split("\n")
.map(|s| s.to_string()) // Convert &str to String
.collect();
也可以看看:
  • Temporary value dropped while borrowed, but I don't want to do a let
  • Using a `let` binding to increase a values lifetime
  • "borrowed value does not live long enough" seems to blame the wrong thing
  • Why does the compiler tell me to consider using a `let` binding" when I already am?
  • Do I need to use a `let` binding to create a longer lived value?
  • Why is it legal to borrow a temporary?
  • 关于rust - 如何从文件中读取字符串,将其拆分,然后在一条语句中创建Vec <&str>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65221920/

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