How do I use floating point number literals when using generic types?

前端 未结 3 1420
庸人自扰
庸人自扰 2020-11-29 12:39

Regular float literals do not work:

extern crate num_traits;

use num_traits::float::Float;

fn scale_float(x: T) -> T {
    x * 0.54
}

f         


        
3条回答
  •  悲哀的现实
    2020-11-29 13:12

    In certain cases, you can add a restriction that the generic type must be able to be multiplied by the type of the literal. Here, we allow any type that can be multiplied by a f64 so long as it produces the output type of T via the trait bound Mul:

    use num_traits::float::Float; // 0.2.6
    use std::ops::Mul;
    
    fn scale_float(x: T) -> T
    where
        T: Float + Mul,
    {
        x * 0.54
    }
    
    fn main() {
        let a: f64 = scale_float(1.23);
    }
    

    This may not work directly for the original problem, but it might depending on what concrete types you need to work with.

提交回复
热议问题