Cannot infer type for Option<T> when passed None

I have a struct with generics like this:

struct Foo<T> {
    member: Option<T>,
}

impl<T> Foo<T> {
    pub fn new(member: Option<T>) -> Self {
        Foo { member }
    }
}

but when calling new with None, Rust cannot infer the type for T:

let y = Foo::new(None);
19 |     let y = Foo::new(None);
   |         -   ^^^^^^^^ cannot infer type for type parameter `T`
   |         |
   |         consider giving `y` the explicit type `Foo<T>`, where the type parameter `T` is specified

but what type should I specify for this None input? Here is my playground test.

If you don't care what type you get, just pick any type. The unit type () is a reasonable default choice that shows you aren't using the type for anything:

let y: Foo<()> = Foo::new(None);

On the other hand, if you want to later do something with y that requires a specific type, then you can pick that type explicitly, or let it be inferred based on that later usage.

Thanks, it will work for this case. I missed that in my real code there are trait bounds also for T. A simplified version is like this:

struct Foo<T> 
where T: Fn(usize) -> usize,
{
    member: Option<T>,
}

I would get error for the following:

    let y: Foo<()> = Foo::new(None);

error:

27 |     let y: Foo<()> = Foo::new(None);
   |            ^^^^^^^ expected an `Fn<(usize,)>` closure, found `()`
   |

I am asking because the actual trait bounds in my code is more complex and I was wondering if there is a simple way to infer or specify the type here.

In this specific case you could probably do something like this:

let y: Foo<_> = Foo::new(None);
1 Like

None with a type hint can be written as None::<()>.

1 Like

None::<fn(usize) -> usize> should work.

The lowercase fn types are function pointers, and are the only nameable types that meet Fn trait bounds.

It seems to me that the trait bounds in my code is too complex for adopting the suggested approaches, I ended up with a different design that don't need the Option<T> . Somehow I guess the complexity of generics / trait bounds forced me to find a simpler (and better I hope) design :wink:

Btw, the trait bounds for Option<F> in my code was something like:

    where
        F: Fn(Request<Body>) -> S + Send + Clone + 'static,
        S: Future<Output = Response<Body>>,

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.