How to use generics with float types and UFCS? Or is there a way to use generics in the module system?


How to use generics with float types and UFCS? I’ve seen the num-traits crate and tried it, and it works fine until I want to use UFCS with a primitive type. For instance, in the code,

let a = f64::floor( b * 275.0 + c );

However, I cannot replace the f64 with the generic type T. I understand I should be able to do,

let a = ( b * 275.0 + c).floor();

and get the same result, but the former seems more straight forward from a math perspective and easier to read and understand the intent. Is there anyway I can use generics with the module system so I can do it the first way with a generic float type instead of just f64?

Maybe a way I haven’t thought of to use macro_rules to interact with the modules and get the desired behavior?



Can you give a complete example of the code you tried to write that did not work? I have not used num-traits before but this works for me:

extern crate num_traits;
use num_traits::{Float, NumCast};

fn main() {
    println!("{}", compute(2.0, 2.0));

fn compute<T: Float>(b: T, c: T) -> T {
    T::floor(b * NumCast::from(275.0).unwrap() + c)


Well great. Your code works, now I have to figure out why mine didn’t. For now I’m abandoning this and just writing it up using f64. Once I have a working implementation, I’ll go back and try to make it generic.

Thanks for the NumCast code, that was really tripping me up too, how to cast with a generic number type.

Is there a group/plan somewhere for standardizing some of this and putting it back into std? I’d like to at least follow it.