如何在 Rust 中绑定“输出”类型的运算符特征?

flmng0

我想使用以下代码:

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,但我假设编译器不知道。

有没有办法解决这个问题,还是我应该像在夜间版中那样按类型实现它?

观星者

带有原语的泛型并不是那么简单。修复第一个错误会揭示其他错误,因为您T0.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
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章