Search code examples
genericsrustcastingprimitive-types

How to cast a generic type to primitive type


I am newbye with Rust. I don't know how to cast generic type <T> to primitive type.

There is a tiny example a function sum with generic types:

fn sum<T: std::ops::Add<Output = T>, U>(x:T, y: U) -> T {
    // is there any line of code similar to:
    // x + y as T
    
    x + y as T
    
    // or check the type
    // match type(x) {
    //    i32 => x + y as i32,
    //    i64 => x + y as i64,
    //    f32 => x + y as f32,
    //    _ => 0
    // }
}

fn main() {
    let a = 1;
    let b = 22.22;
    println!("{}", sum(a, b));
    
    let a = 11.11;
    let b = 2;
    println!("{}", sum(a, b));
}

Solution

  • The initial thought might be to require U: Into<T>. However, there is no e.g. impl Into<i32> for f32 so that won't work. Might also think of requiring T: Add<U, Output = T>, however that won't work in your case either for the same reason.

    Instead you could use the num crate, specifically the AsPrimitive trait.

    use std::ops::Add;
    
    // num = "0.3"
    use num::cast::AsPrimitive;
    
    fn sum<T, U>(x: T, y: U) -> T
    where
        T: Copy + 'static,
        T: Add<Output = T>,
        U: AsPrimitive<T>,
    {
        x + y.as_()
    }
    

    With that implementation of sum(), then executing your main() will output the following:

    23
    13.11