Home > Net >  Access method of float type from generic function in Rust
Access method of float type from generic function in Rust

Time:04-02

I try to create a generic function in Rust, that works on all float types and uses a method implemented on f32 and f64:

use num_traits::Float;

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

When I try to compile this code, the compiler tells me that rem_euclid is not defined for 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`

How can I use this method in the generic function?

CodePudding user response:

This works Playground, so I think this function rem_euclid doesn't exist on Float trait.

You can create a trait that has the function you want too. Playground

CodePudding user response:

From looking at the documentation for num_traits it does not contain a function for rem_euclid.

Using the following should give you the same result as rem_euclid and works with the num_traits Float variable type.

use num_traits::Float;

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