Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading