根据是否低于或高于某个其他值来增加或减少某些东西,我可以这样做:
if destination > self.position {
self.position += 1;
} else if destination < self.position {
self.position -= 1;
}
或者这个:
self.position += match self.position.cmp(&destination) {
Ordering::Less => {
1
}
Ordering::Greater => {
-1
}
Ordering::Equal => {
0
}
}
后者是IMO更清晰,但更冗长。有没有办法将这些Ordering
值转换为整数(-1,0,1),类似于PHP's spaceship operator,否则会降低此代码的详细程度?
答案 0 :(得分:4)
是的,您可以将它们转换为有符号整数(可在the source of cmp::Ordering中验证):
use std::cmp::Ordering;
fn main() {
println!("{}", Ordering::Less as i8); // -1
println!("{}", Ordering::Equal as i32); // 0
println!("{}", Ordering::Greater as i64); // 1
}
在您的情况下,可以按如下方式使用:
self.position -= self.position.cmp(&destination) as i8; // or a different, more suitable signed integer
答案 1 :(得分:1)
像@ljedrz所说,你可以将Ordering
转换为整数。另一个可能更清楚的选择是记住你可以使用if
作为表达式:
self.position += if destination > self.position { 1 }
else if destination < self.position { -1 }
else { 0 };