使用泛型类型时如何使用浮点数文字? [英] How do I use floating point number literals when using generic types?

查看:82
本文介绍了使用泛型类型时如何使用浮点数文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常规浮点文字不起作用:

Regular float literals do not work:

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}`

推荐答案

使用 FromPrimitive性状:

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

另请参阅:

这篇关于使用泛型类型时如何使用浮点数文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆