Rust 书提供了两个(此处相关)如何使用的示例BufRead。他们首先给出了一个“适合初学者”的例子,然后再介绍一个更“有效的方法”。
初学者友好的示例逐行读取文件:
use std::fs::File;
use std::io::{ self, BufRead, BufReader };
fn read_lines(filename: String) -> io::Lines<BufReader<File>> {
// Open the file in read-only mode.
let file = File::open(filename).unwrap();
// Read the file line by line, and return an iterator of the lines of the file.
return io::BufReader::new(file).lines();
}
fn main() {
// Stores the iterator of lines of the file in lines variable.
let lines = read_lines("./hosts".to_string());
// Iterate over the lines of the file, and in …Run Code Online (Sandbox Code Playgroud) 我希望将String使用format!宏创建的a转换为 a&str并使用let绑定将其分配给一个值:
fn main() {
let my_bool = true;
let other = String::from("my_string");
let result = if my_bool {
format!("_{}", other).as_str()
} else {
"other"
};
println!("{}", result);
}
Run Code Online (Sandbox Code Playgroud)
(锈游乐场)
当我这样做时,编译器抱怨String在语句的末尾释放了临时值(根据我的理解),这意味着我无法动态创建&str:
fn main() {
let my_bool = true;
let other = String::from("my_string");
let result = if my_bool {
format!("_{}", other).as_str()
} else {
"other"
};
println!("{}", result);
}
Run Code Online (Sandbox Code Playgroud)
我一直试图了解 Rust 的生命周期系统,但我无法真正理解这个系统。Rust 建议如下:
error[E0716]: temporary value dropped …Run Code Online (Sandbox Code Playgroud)