if let 语句中的类型不匹配:找到选项预期结果

rpi*_*per 5 rust

我正在尝试解析一个文件,该文件在每个值之间都有一个管道分隔符,每行都是一条新记录。我像这样迭代每一行:

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因此假设我没有遗漏任何东西,在结果之前解开它是有意义的。

sep*_*p2k 3

您链接到 的文档next,但您没有使用next(无论如何不是直接使用),您正在使用 for 循环。line在 for 循环中,迭代变量的类型(即代码中的类型)是Item迭代器的类型,在您的情况下是Result<String>

的类型nextOption<Item>因为您可能调用next已经到达末尾的迭代器。for 循环的主体在迭代结束后永远不会执行,因此迭代变量作为选项是没有意义的。

  • @rpiper 是的,但它更符合“如果下一个返回 Some(x) 将 `x` 分配给循环变量,否则结束循环”。 (3认同)
  • @rpiper *for 循环直接利用 `next` 函数* - 是的,它确实在内部使用了 `next`。它为您处理“Some”或“None”的情况,在“Some”时执行主体,在“None”时退出循环。 (2认同)