这个问题在这里已有答案:
我想使用以下代码:
use std::ops::Rem;
fn modulo<T: PartialOrd + Rem>(num: T, det: T) -> T {
let num = num % det;
if num < 0.0 {
num + det.abs()
} else {
num
}
}
这只是取自实验性euclidean_division
特征的通用代码。提供的错误如下:
error[E0369]: binary operation `<` cannot be applied to type `<T as std::ops::Rem>::Output`
--> src/lib.rs:5:8
|
5 | if num < 0.0 {
| ^^^^^^^^^
|
= note: an implementation of `std::cmp::PartialOrd` might be missing for `<T as std::ops::Rem>::Output`
error[E0599]: no method named `abs` found for type `T` in the current scope
--> src/lib.rs:6:19
|
6 | num + det.abs()
| ^^^
error[E0369]: binary operation `+` cannot be applied to type `<T as std::ops::Rem>::Output`
--> src/lib.rs:6:9
|
6 | num + det.abs()
| ^^^^^^^^^^^^^^^
|
= note: an implementation of `std::ops::Add` might be missing for `<T as std::ops::Rem>::Output`
error[E0308]: mismatched types
--> src/lib.rs:8:9
|
3 | fn modulo<T: PartialOrd + Rem>(num: T, det: T) -> T {
| - expected `T` because of return type
...
8 | num
| ^^^ expected type parameter, found associated type
|
= note: expected type `T`
found type `<T as std::ops::Rem>::Output`
显然Rem::rem
的输出应该与T
的输出类型相同,但我认为编译器并不知道。
有没有办法解决这个问题,或者我应该按照每晚的版本以同样的方式实现它?
具有基元的泛型并非如此简单。修复第一个错误会显示其他错误,因为您将T
与0.0
进行比较。有很多方法可以解决这些问题;这是使用num
的一种方式:
use num::{Signed, Zero};
use std::ops::Rem;
fn modulo<T>(num: T, det: T) -> T
where
T: Rem<Output = T>,
T: PartialOrd,
T: Zero,
T: Signed,
T: Copy,
{
let num = num % det;
if num < T::zero() {
num + det.abs()
} else {
num
}
}