【问题标题】:How do I use floating point number literals when using generic types?使用泛型类型时如何使用浮点数文字?
【发布时间】:2018-06-08 20:22:13
【问题描述】:

常规浮点文字不起作用:

extern crate num_traits;

use num_traits::float::Float;

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

fn main() {
    let a: f64 = scale_float(1.23);
}
error[E0308]: mismatched types
 --> src/main.rs:6:9
  |
6 |     x * 0.54
  |         ^^^^ expected type parameter, found floating-point variable
  |
  = note: expected type `T`
             found type `{float}`

【问题讨论】:

    标签: floating-point rust traits literals


    【解决方案1】:

    使用FromPrimitive trait

    use num_traits::{cast::FromPrimitive, float::Float};
    
    fn scale_float<T: Float + FromPrimitive>(x: T) -> T {
        x * T::from_f64(0.54).unwrap()
    }
    

    或者标准库From/Intotraits

    fn scale_float<T>(x: T) -> T
    where
        T: Float,
        f64: Into<T>
    {
        x * 0.54.into()
    }
    

    另见:

    【讨论】:

    • 谢谢。第一个有效,第二个无效,因为缺少 f64->f32 转换。固定在playground。组装检查表明这是零成本,所以我很高兴!
    • @goertzenator 你可以走另一条路 (f32: Into&lt;T&gt;)。
    【解决方案2】:

    如今,numeric_literals crate 及其 replace_float_literals 功能有助于对复杂代码进行必要的替换。

    【讨论】:

      【解决方案3】:

      在某些情况下,您可以添加一个限制,即泛型类型必须能够乘以文字的类型。在这里,我们允许任何可以乘以 f64 的类型,只要它通过 trait bound Mul&lt;f64, Output = T&gt; 产生 T 的输出类型:

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

      这可能无法直接解决原始问题,但可能取决于您需要使用的具体类型。

      【讨论】:

        【解决方案4】:

        您不能直接从文字创建Float。我建议一种类似于FloatConst trait 的方法:

        trait SomeDomainSpecificScaleFactor {
            fn factor() -> Self;
        }
        
        impl SomeDomainSpecificScaleFactor for f32 {
            fn factor() -> Self {
                0.54
            }
        }
        
        impl SomeDomainSpecificScaleFactor for f64 {
            fn factor() -> Self {
                0.54
            }
        }
        
        fn scale_float<T: Float + SomeDomainSpecificScaleFactor>(x: T) -> T {
            x * T::factor()
        }
        

        (link to playground)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-22
          • 1970-01-01
          • 1970-01-01
          • 2021-09-21
          • 1970-01-01
          相关资源
          最近更新 更多