以下代码(游乐场)
let max_column = 7;
edge = match current_column {
0 => Edge::Left,
max_column => Edge::Right,
_ => Edge::NotAnEdge
};
Run Code Online (Sandbox Code Playgroud)
导致以下错误:
warning: unreachable pattern
--> src/main.rs:10:9
|
9 | max_column => Edge::Right,
| ---------- matches any value
10 | _ => Edge::NotAnEdge
| ^ unreachable pattern
|
= note: #[warn(unreachable_patterns)] on by default
Run Code Online (Sandbox Code Playgroud)
max_column用文字替换变量可以正常工作:
let max_column = 7;
edge = match current_column {
0 => Edge::Left,
7 => Edge::Right,
_ => Edge::NotAnEdge
};
Run Code Online (Sandbox Code Playgroud)
为什么_在第一个示例中无法访问任何值current_column …
我在Rust中实现了一个解析器,而空白是我想在match模式中重用的常见模式.
此代码有效:
let ch = ' ';
match ch {
' ' | '\n' | '\t' | '\r' => println!("whitespace"),
_ => println!("token"),
}
Run Code Online (Sandbox Code Playgroud)
如果我每次都需要继续指定空白模式,这将变得非常重复.我想定义一次并重用它.我想做的事情如下:
let whitespace = ' ' | '\n' | '\t' | '\r';
let ch = ' ';
match ch {
whitespace => println!("whitespace"),
_ => println!("token"),
}
Run Code Online (Sandbox Code Playgroud)
编译器不喜欢ws赋值.它将其解释|为二进制运算而不是交替运算.
模式可以以某种方式存储在变量中吗?有没有更好或更惯用的方法来做到这一点?
rust ×2