此错误消息是否意味着我可以在 for 循环中使用模式匹配? [英] Does this error message mean I can use pattern matching in for loops?
问题描述
我不希望下面的代码能工作,但作为语法探索的一部分,我尝试了 游乐场:
I do not expect the following code to work, but as part of grammar exploration, I tried in playground:
fn main() {
struct EOF {};
let lines = vec![Ok("line 1"), Ok("line 2"), Err(EOF {})];
for Ok(line) in lines {
println!("{}", line);
}
}
错误信息是
error[E0005]: refutable pattern in `for` loop binding: `Err(_)` not covered
--> src/main.rs:4:9
|
4 | for Ok(line) in lines {
| ^^^^^^^^ pattern `Err(_)` not covered
根据上面的消息,看起来我只需要为 Err
情况添加一个匹配臂.但是这样做的正确语法是什么?
According to the message above it looks like I only need to add a match arm for the Err
case. But what is the right grammar to do so?
推荐答案
您可以使用 patterns 作为 for
循环中的绑定,但不能refutable 模式.此处描述了可反驳和不可反驳的模式之间的区别,但是它的要点是,如果模式可能失败,则不能在 let
语句、for
循环、函数或闭包的参数中使用它,或者语法特别需要无可辩驳的模式的其他地方.
You can use patterns as the binding in a for
loop, but not refutable patterns. The difference between refutable and irrefutable patterns is described here, but the gist of it is, if a pattern could fail, you can't use it in a let
statement, a for
loop, the parameter of a function or closure, or other places where the syntax specifically requires an irrefutable pattern.
一个在 for
循环中使用的无可辩驳的模式的例子可能是这样的:
An example of an irrefutable pattern being used in a for
loop might be something like this:
let mut numbers = HashMap::new();
numbers.insert("one", 1);
numbers.insert("two", 2);
numbers.insert("three", 3);
for (name, number) in &numbers {
println!("{}: {}", name, number);
}
(name, number)
是一个无可辩驳的模式,因为任何它类型检查的地方,它都会匹配.它在这里进行类型检查,因为正在迭代的项目(由 的实现定义)IntoIterator
for &HashMap
) 是元组.你也可以把上面写成
(name, number)
is an irrefutable pattern, because any place where it type checks, it will match. It type checks here because the items being iterated over (defined by the implementation of IntoIterator
for &HashMap
) are tuples. You could also write the above as
for tuple in &numbers {
let (name, number) = tuple;
println!("{}: {}", name, number);
}
因为 let
是另一个只允许无可辩驳的模式的地方.
because let
is another place where only irrefutable patterns are allowed.
这篇关于此错误消息是否意味着我可以在 for 循环中使用模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!