Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type Casting Option in rust

Tags:

casting

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,
    };
}

like image 357
developomp Avatar asked Aug 03 '26 01:08

developomp


1 Answers

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.

like image 190
Netwave Avatar answered Aug 05 '26 19:08

Netwave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!