gpt4 book ai didi

rust - 是否有从 Rust 的 Ordering::* 到整数的内置转换?

转载 作者:行者123 更新时间:2023-11-29 08:11:24 25 4
gpt4 key购买 nike

要根据某个值是低于还是高于某个其他值来增加或减少某些东西,我可以这样做:

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 ,或者以其他方式减少这段代码的冗长程度?

最佳答案

是的,您可以将它们转换为有符号整数(可以在 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

关于rust - 是否有从 Rust 的 Ordering::* 到整数的内置转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47767954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com