Search code examples
rustcasting

Type Casting Option in rust


How do I cast optional values in rust?

This is what I came up with, which does work, but I think there must be a more elegant way.

pub fn option_t_to_i32_option<T1, T2>(optional_val: Option<T1>) -> Option<T2>
where
    T2: From<T1>,
{
    return match optional_val {
        Some(val) => Some(T2::from(val)),
        None => None,
    };
}


Solution

  • Just map Into::into for your constrains:

    pub fn option_t_to_i32_option<T1, T2>(optional_val: Option<T1>) -> Option<T2>
    where
        T2: From<T1>,
    {
        optional_val.map(Into::into)
    }
    

    Playground

    As per your function name, maybe you would like to actually match the output type to i32:

    pub fn option_t_to_i32_option<T1>(optional_val: Option<T1>) -> Option<i32>
    where
        T1: Into<i32>,
    {
        optional_val.map(Into::into)
    }
    

    Playground

    Btw, since this is a wrapper, you could rather use _.map(Into::into) wherever you need to go Option<T> => Option<i32> instead.