floating-point - 使用泛型时如何使用 float 文字?

标签 floating-point rust traits literals

常规浮点文字不起作用:

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 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 traits

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

另见:

关于floating-point - 使用泛型时如何使用 float 文字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50767912/

相关文章:

rust - Rust 中是否可以有一个包含不同结构的二进制堆?

c - 如何在c中将输出精度设置为float

c - 为什么 "for( i = 0.1 ; i != 1.0 ; i += 0.1)"在 i = 1.0 时不中断?

iterator - 返回依赖于函数内分配的数据的惰性迭代器

rust - 包装 C lib 初始化/销毁例程的推荐方法

php - 我可以从类外部的特征中调用静态函数吗?

c - WebAssembly:(f32.const nan:0x200000) 表示 0x7fa00000 或 0x7fe00000

C 从二进制 float

rust - `cargo package` : error: main function not found

scala - 为什么val和def实现抽象方法的时间不同?