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


instead of


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 {

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() {

Are these backwards compatible? So it'll work for both
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.