简体   繁体   English

从特征和泛型函数

[英]From traits and generic function

I am trying to create a generic function as below:我正在尝试创建一个通用函数,如下所示:

use std::ops::Add;
use std::ops::DivAssign;

fn normalize<T>(vec: &mut Vec<Vec<T>>, bd: u32)
where
    T: DivAssign + Add<Output = T> + From<i32> + From<i16>,
{
    let max_value = match bd {
        16 => T::from(i16::MAX) + T::from(1_i16),
        32 => T::from(i32::MAX) + T::from(1_i32),
        _ => panic!("unsuported bit depth"),
    };

    for ch in 0..vec.len() {
        vec[ch].iter_mut().for_each(|x| *x /= max_value);
    }
}

When I call the function I am getting an error:当我调用该函数时,出现错误:

normalize::<f32>(&mut vec![vec![1_f32,2_f32,3_f32]], 16_u32);

the trait bound `f32: From<i32>` is not satisfied
the following implementations were found:
  <f32 as From<i16>>
  <f32 as From<i8>>
  <f32 as From<u16>>
  <f32 as From<u8>>rustcE0277
misc.rs(19, 38): required by a bound in `normalize`

Could someone explain me what's going on and how can I fix it?有人可以向我解释发生了什么,我该如何解决?

From is only available when conversions are lossless. From仅在转换无损时可用。

Single-precision floats have a 23-bit significand.单精度浮点数具有 23 位有效数。 They can only represent the full integer range from 0 to 2 24 .它们只能表示从 0 到 2 24完整整数范围 Any higher than that and there are integers that can't be represented.任何高于此值的整数都无法表示。

Demonstration:示范:

println!("{} as f32 = {}", 16777213i32, 16777213i32 as f32); // 2**24 - 3
println!("{} as f32 = {}", 16777214i32, 16777214i32 as f32); // 2**24 - 2
println!("{} as f32 = {}", 16777215i32, 16777215i32 as f32); // 2**24 - 1
println!("{} as f32 = {}", 16777216i32, 16777216i32 as f32); // 2**24
println!("{} as f32 = {}", 16777217i32, 16777217i32 as f32); // 2**24 + 1
println!("{} as f32 = {}", 16777218i32, 16777218i32 as f32); // 2**24 + 2
println!("{} as f32 = {}", 16777219i32, 16777219i32 as f32); // 2**24 + 3

Output:输出:

16777213 as f32 = 16777213
16777214 as f32 = 16777214
16777215 as f32 = 16777215
16777216 as f32 = 16777216
16777217 as f32 = 16777216
16777218 as f32 = 16777218
16777219 as f32 = 16777220

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM