使用泛型类型时如何使用浮点数文字?

问题描述 投票:1回答:3

常规浮点文字不起作用:

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
3个回答
3
投票

使用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 / Into特征

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

也可以看看:


1
投票

你不能直接从文字创建Float。我建议采用类似于FloatConst特征的方法:

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()
}

(Qazxswpoi)


0
投票

在某些情况下,您可以添加一个限制,通用类型必须能够乘以文字的类型。在这里,我们允许任何可以乘以link to playground的类型,只要它通过特征绑定f64产生T的输出类型:

Mul<f64, Output = T>

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

© www.soinside.com 2019 - 2024. All rights reserved.