简体   繁体   English

从Rust的Ordering :: *到整数有内置的转换吗?

[英]Is there a built-in conversion from Rust's Ordering::* to integers?

To increment or decrement something based on whether it's below or above some other value, I can do this: 要根据某值是低于还是高于其他值来递增或递减,我可以这样做:

if destination > self.position {
    self.position += 1;
} else if destination < self.position {
    self.position -= 1;
}

or this: 或这个:

self.position += match self.position.cmp(&destination) {
    Ordering::Less => {
        1
    }
    Ordering::Greater => {
        -1
    }
    Ordering::Equal => {
        0
    }
}

The latter is IMO clearer, but much more verbose. 后者更加清晰,但更为冗长。 Is there a way convert these Ordering values to integers (-1, 0, 1), similar to PHP's spaceship operator , or otherwise reduce the verbosity of this code? 有没有一种方法可以将这些Ordering值转换为整数(-1、0、1),类似于PHP的spaceship运算符 ,还是可以减少此代码的冗长性?

Yes, you can cast them to signed integers (which can be verified in the source of cmp::Ordering ): 是的,您可以将它们转换为带符号的整数(可以在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
}

In your case this could be used as follows: 在您的情况下,可以按以下方式使用:

self.position -= self.position.cmp(&destination) as i8; // or a different, more suitable signed integer

Like @ljedrz said, you can convert the Ordering to an integer. 就像@ljedrz所​​说的那样,您可以将Ordering转换为整数。 Another option, which may be clearer is to remember that you can use if as an expression: 另一种可能更清楚的选择是记住可以将if用作表达式:

self.position += if destination > self.position      {  1 }
                 else if destination < self.position { -1 }
                 else                                {  0 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM