How to implement optional arguments (`Into<Option<S>>`) with `AsRef` trait?

I'm trying to implement a function with optional arguments:

fn optional_args<S>(arg0: impl Into<Option<S>>)
where
    S: AsRef<str>,
{
    unimplemented!()
}

But I can't call the function with None argument:

fn main() {
    optional_args::<String>(None::<String>);
}
error[E0632]: cannot provide explicit generic arguments when `impl Trait` is used in argument position
 --> src/main.rs:2:21
  |
2 |     optional_args::<String>(None::<String>);
  |                     ^^^^^^ explicit generic argument not allowed

What am I doing wrong?

As the error message says, you cannot explicitly specify the generic types when you use the impl Trait syntax for an argument. Change it to use generics:

fn optional_args<S, I>(arg0: I)
where
    S: AsRef<str>,
    I: Into<Option<S>>,
{
    unimplemented!()
}

Or, maybe just simplify your life a bit like this:

fn optional_args<S: AsRef<str>>(arg0: Option<S>) {
    unimplemented!()
}
1 Like

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.