From and Into traits and conversion of usize to f64

后端 未结 2 1050
我寻月下人不归
我寻月下人不归 2021-01-12 17:23

I\'ve been trying to write some Rust code in a very generic way, without specifying the types explicitly. However, I arrived at a point where I need to convert a usiz

相关标签:
2条回答
  • 2021-01-12 18:09

    You can do it using as:

    let num: f64 = 12 as f64 ;
    
    0 讨论(0)
  • 2021-01-12 18:12

    The problem is that integer → floating point conversions, where the float type is the same size or smaller than the integer, cannot preserve all values. So usizef64 loses precision on 64-bit.

    These sorts of conversions are basically the raison d'être for the conv crate, which defines numerous fallible conversions between types (mostly built-in numeric ones). This (as of 10 minutes ago) includes isize/usizef32/f64.

    Using conv, you can do this:

    use conv::prelude::*;
    
    ...
    
    where T: ValueFrom<usize> + ...
    
    ...
    ans[k] = ans[k - 1] / (k + 1).value_as::<T>().unwrap();
    ...
    

    Disclaimer: I am the author of the crate in question.

    0 讨论(0)
提交回复
热议问题