Rust中泛型函数访问float类型的方法

Access method of float type from generic function in Rust

我尝试在 Rust 中创建一个通用函数,它适用于所有浮点类型并使用在 f32f64 上实现的方法:

use num_traits::Float;

fn foo<F: Float>( a: F, b: F ) -> F {
    return a.rem_euclid( b );
}

当我尝试编译这段代码时,编译器告诉我 rem_euclid 没有为 F 定义:

 no method named `rem_euclid` found for type parameter `F` in the current scope
  --> src\lib.rs:54:11
   |
54 |     return a.rem_euclid( b );
   |              ^^^^^^^^^^ method not found in `F`

如何在通用函数中使用此方法?

这有效 Playground, so I think this function rem_euclid doesn't exist on Float trait

您也可以创建具有您想要的功能的特征。 Playground

通过查看 num_traits 的文档,它不包含 rem_euclid 的函数。

使用以下内容应该会得到与 rem_euclid 相同的结果,并且适用于 num_traits Float 变量类型。

use num_traits::Float;

fn foo<F: Float>( a: F, b: F ) -> F {
    return (a - (a / b).trunc() * b).abs();
}

f32/f64 的欧几里得模方法在 libcore, and it is not in Float trait

您可以尝试像这样实现您的 fn,语法没问题

trait FloatNumber {
    fn rem_euclid(self, rhs: Self) -> Self;
}

impl FloatNumber for f32 {
    fn rem_euclid(self, rhs: Self) -> Self {
         self.rem_euclid(rhs)
    }
}

impl FloatNumber for f64 {
   fn rem_euclid(self, rhs: Self) -> Self {
      self.rem_euclid(rhs)
 }
}

fn foo<T: FloatNumber>(a: T, b: T) -> T {
    return a.rem_euclid(b);
}