[英]Mismatched types in if let statement: found Option expected Result
I am trying to parse a file that has a pipe delimiter between each value and each line is a new record. 我试图解析一个文件,在每个值之间有一个管道分隔符,每一行都是一个新记录。 I am iterating over each line like this:
我正在迭代每一行,如下所示:
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");
}
}
}
However, I get an error: 但是,我收到一个错误:
error[E0308]: mismatched types
--> src/main.rs:9:20
|
9 | if let Some(channel_line) = line {
| ^^^^^^^^^^^^^^^^^^ expected enum `std::result::Result`, found enum `std::option::Option`
|
= note: expected type `std::result::Result<std::string::String, std::io::Error>`
= note: found type `std::option::Option<_>`
This error is confusing to me as the found type is what I expected namely Option<Result<String, Error>>
as indicated by the docs so it would make sense to unwrap the Option
before the result assuming I am not missing something. 这个错误让我感到困惑,因为找到的类型是我所期望的,即文档所指示的
Option<Result<String, Error>>
所以在假设我没有遗漏某些内容之前在结果之前解包Option
有意义的。
You linked to the documentation of next
, but you're not using next
(not directly anyway), you're using a for loop. 你链接到
next
的文档,但是你没有使用next
(不是直接使用),你正在使用for循环。 In a for loop the type of the iteration variable (ie the type of line
in your code) is the Item
type of the iterator, which in your case is Result<String>
. 在for循环中,迭代变量的类型(即代码中的
line
的类型)是迭代器的Item
类型,在您的情况下是Result<String>
。
The type of next
is Option<Item>
because you might call next
on an iterator that already reached the end. next
类型是Option<Item>
因为您可能会在已经到达结尾的迭代器上调用next
。 The body of a for loop won't ever execute after the end of the iteration, so there's no point in the iteration variable being an option. for循环的主体在迭代结束后不会执行,因此迭代变量中没有任何一个选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.