我想使用以下代码:
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
的类型相同,但是我认为编译器并不知道这一点。
是否有解决此问题的方法,还是应该按夜间版本中的相同方式按类型实现它?
答案 0 :(得分:2)
带有原语的泛型不是那么简单。修正第一个错误会揭示其他错误,因为您将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
}
}