Auto convert T to Option<T>

I have a function

fn some_func(num: Option<u32>){
    match num{
        Some(val) => ....,
        None => ....,
    }
}

I want to call it like

some_func(3);

instead of

some_func(Some(3));

What is a good way to do this?

I tried to implement From<u32> for Option<u32>

impl From<u32> for Option<u32> {
    fn from(num: u32) -> Self {
        Some(num)
    }
}

But this show the error

conflicting implementations of trait std::convert::From<u32> for type std::option::Option<u32>:
conflicting implementation in crate core:

  • impl std::convert::From for std::option::Option;rustc(E0119)

only traits defined in the current crate can be implemented for arbitrary types
define and implement a trait or new type insteadrustc(E0117)

What can I do instead?

Or more generally speaking, what is the best way to represent optional parameters?

These traits have already been implemented, you can simply use them:

fn some_func<T: Into<Option<u32>>>(num: T){
    let num: Option<u32> = num.into();
    match num {
        Some(val) => {},
        None => {},
    }
}

fn main() {
    some_func(1);
    some_func(Some(2));
}
6 Likes

Are these backwards compatible? So it'll work for both
some_func(3);
and also
some_func(Some(3)); ?

Yes, every type implements From and Into for itself, thanks to an implementation of From<T> for T in the standard library.

1 Like

Thanks guys, it worked. For backward compatibility as well.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.