使用对比较运算符或函数的引用来比较某些值
Use a reference to a compare operator or function to compare some values
有没有办法在 Rust 中引用比较运算符或函数来比较某些值?所以我的想法是...
enum SomeEnum {
A,
B,
}
let some_enum = SomeEnum::A;
let a = 1;
let b = 2;
// What would be nice ...
let op = match some_enum {
SomeEnum::A => {
ge_operator // return greater_equal operator - how could this work?
}
SomeEnum::B => {
ls_operator // return less operator - how could this work?
}
};
let test = if a op b {
'X'
} else {
'Y'
};
您可以return 函数根据需要在匹配范围内:
// What would be nice ...
let op = match some_enum {
SomeEnum::A => {
<u32 as PartialOrd<u32>>::ge // return greater_equal operator - how could this work?
}
SomeEnum::B => {
<u32 as PartialOrd<u32>>::lt // return less operator - how could this work?
}
};
正如@eggyal 指出的,rust 甚至可以推断类型:
let op = match some_enum {
SomeEnum::A => PartialOrd::ge,
SomeEnum::B => PartialOrd::lt,
};
有没有办法在 Rust 中引用比较运算符或函数来比较某些值?所以我的想法是...
enum SomeEnum {
A,
B,
}
let some_enum = SomeEnum::A;
let a = 1;
let b = 2;
// What would be nice ...
let op = match some_enum {
SomeEnum::A => {
ge_operator // return greater_equal operator - how could this work?
}
SomeEnum::B => {
ls_operator // return less operator - how could this work?
}
};
let test = if a op b {
'X'
} else {
'Y'
};
您可以return 函数根据需要在匹配范围内:
// What would be nice ...
let op = match some_enum {
SomeEnum::A => {
<u32 as PartialOrd<u32>>::ge // return greater_equal operator - how could this work?
}
SomeEnum::B => {
<u32 as PartialOrd<u32>>::lt // return less operator - how could this work?
}
};
正如@eggyal 指出的,rust 甚至可以推断类型:
let op = match some_enum {
SomeEnum::A => PartialOrd::ge,
SomeEnum::B => PartialOrd::lt,
};