没有解构的匹配臂中的条件
Conditions in a match arm without destructuring
use std::cmp::Ordering;
fn cmp(a: i32, b: i32) -> Ordering {
match {
_ if a < b => Ordering::Less,
_ if a > b => Ordering::Greater,
_ => Ordering::Equal,
}
}
fn main() {
let x = 5;
let y = 10;
println!("{}", match cmp(x, y) {
Ordering::Less => "less",
Ordering::Greater => "greater",
Ordering::Equal => "equal",
});
}
如何在上面的函数 cmp
中使用带条件的 match
而无需解构(因为没有任何东西可以解构)?
代码改编自书中著名的示例,仅使用了if/else,但是,它不起作用:
src/main.rs:5:9: 5:10 error: unexpected token: `_`
src/main.rs:5 _ if a < b => Ordering::Less,
^
Could not compile `match_ordering`.
我正在使用 rustc 1.0.0-nightly (3ef8ff1f8 2015-02-12 00:38:24 +0000)
。
这可行:
fn cmp(a: i32, b: i32) -> Ordering {
match (a, b) {
(a,b) if a < b => Ordering::Less,
(a,b) if a > b => Ordering::Greater,
_ => Ordering::Equal,
}
}
但它会使用解构。有没有其他方式,或者这只是最惯用、最简洁的编写方式?
您需要匹配某些东西,即 match { ... }
无效,因为 match
和 {
之间需要有东西。由于您不关心值本身,因此匹配单位 ()
应该没问题:match () { ... }
,例如:
match () {
_ if a < b => Ordering::Less,
_ if a > b => Ordering::Greater,
_ => Ordering::Equal
}
(严格来说:match { _ => ... }
实际上是试图将 { ... }
解析为匹配头(即匹配的表达式),而 _
在表达式的开头,因此是错误。)
关于惯用性:我个人认为用 match
和一系列 _ if ...
来表达具有简短结果的一系列条件(像这样)很好。
use std::cmp::Ordering;
fn cmp(a: i32, b: i32) -> Ordering {
match {
_ if a < b => Ordering::Less,
_ if a > b => Ordering::Greater,
_ => Ordering::Equal,
}
}
fn main() {
let x = 5;
let y = 10;
println!("{}", match cmp(x, y) {
Ordering::Less => "less",
Ordering::Greater => "greater",
Ordering::Equal => "equal",
});
}
如何在上面的函数 cmp
中使用带条件的 match
而无需解构(因为没有任何东西可以解构)?
代码改编自书中著名的示例,仅使用了if/else,但是,它不起作用:
src/main.rs:5:9: 5:10 error: unexpected token: `_`
src/main.rs:5 _ if a < b => Ordering::Less,
^
Could not compile `match_ordering`.
我正在使用 rustc 1.0.0-nightly (3ef8ff1f8 2015-02-12 00:38:24 +0000)
。
这可行:
fn cmp(a: i32, b: i32) -> Ordering {
match (a, b) {
(a,b) if a < b => Ordering::Less,
(a,b) if a > b => Ordering::Greater,
_ => Ordering::Equal,
}
}
但它会使用解构。有没有其他方式,或者这只是最惯用、最简洁的编写方式?
您需要匹配某些东西,即 match { ... }
无效,因为 match
和 {
之间需要有东西。由于您不关心值本身,因此匹配单位 ()
应该没问题:match () { ... }
,例如:
match () {
_ if a < b => Ordering::Less,
_ if a > b => Ordering::Greater,
_ => Ordering::Equal
}
(严格来说:match { _ => ... }
实际上是试图将 { ... }
解析为匹配头(即匹配的表达式),而 _
在表达式的开头,因此是错误。)
关于惯用性:我个人认为用 match
和一系列 _ if ...
来表达具有简短结果的一系列条件(像这样)很好。