Rust: define generic of impl is not an Option

Viewed 78

Can I say this implementation is not for Option<_> or add priority for impl?

I know I can add type to let y: Foo<_>, but I want to use auto infer.

enum Foo<T> {
     Value(T),
     Some(T),
     None,
}

// only for non-option T types.
impl<T> From<T> for Foo<T>
// where !Option<_> ?
{ 
    fn from(value: T) -> Self {
        Foo::Value(value)
    }
}

impl<T> From<Option<T>> for Foo<T> {
    fn from(value: Option<T>) -> Self {
        match value {
            Some(value) => Foo::Some(value),
            None => Foo::None,
         }
    }
}

let the_string = "hello".to_string();
let the_string_option = Some("world".to_string());

let x: Foo<_> = the_string.into();
let y: Foo<_> = the_string_option.into();
let y: Foo<_> = the_string_option.into();
    -  ^^^^^^ cannot infer type
    |
    consider giving `y` the explicit type `with_name::tests::test_multi_value::Foo<_>`, with the type parameters specified
1 Answers

There is no problem with the code. But compiler do not know what implementation of From/Into to use, that is why it asks for the type hint.

It would be solved if you ever use the variable (y in this case) somewhere were is supposed to be of the expected type:

...
let y = the_string_option.into();
    
fn foo(v: Foo<String>) {}
foo(y)

Playground

Related