我正在尝试解析一个文件,该文件在每个值之间都有一个管道分隔符,每行都是一条新记录。我像这样迭代每一行:
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
fn main() {
let source_file = File::open("input.txt").unwrap();
let reader = BufReader::new(source_file);
for line in reader.lines() {
if let Some(channel_line) = line {
println!("yay");
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我收到一个错误:
use std::fs::File;
use std::io::BufReader;
use std::io::prelude::*;
fn main() {
let source_file = File::open("input.txt").unwrap();
let reader = BufReader::new(source_file);
for line in reader.lines() {
if let Some(channel_line) = line {
println!("yay");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个错误让我感到困惑,因为找到的类型是我所期望的,即Option<Result<String, Error>>如文档所示,Option因此假设我没有遗漏任何东西,在结果之前解开它是有意义的。
您链接到 的文档next,但您没有使用next(无论如何不是直接使用),您正在使用 for 循环。line在 for 循环中,迭代变量的类型(即代码中的类型)是Item迭代器的类型,在您的情况下是Result<String>。
的类型next是Option<Item>因为您可能调用next已经到达末尾的迭代器。for 循环的主体在迭代结束后永远不会执行,因此迭代变量作为选项是没有意义的。
| 归档时间: |
|
| 查看次数: |
4098 次 |
| 最近记录: |