Generics error with Option<>


#1

I have the following code:

pub enum RopResult<T, E> {
    Success(T, Option<Vec<E>>),
    Failure(Vec<E>),
}

fn main() {
    let t = RopResult::Success(5, Option::None);
    match t {
        RopResult::Success(x, y) => println!("This is the success {}", x),
        RopResult::Failure(z) => println!("Not what we expected"), 
    }
}

I get the following error:
src\main.rs:6:13: 6:31 error: unable to infer enough type information about_; type annotations or generic parameter binding required [E0282] src\main.rs:6 let t = RopResult::Success(5, Option::None);

Anyone any idea what I did wrong?


#2

What is the type of t - RopResult<i32, ???>?


#3

Sure!

First – this is not really important or related to your problem, but still kind of is – you can just say None instead of Option::None (see https://doc.rust-lang.org/std/prelude/).

Now about the problem itself. What do you think the type of t is? Maybe it’s RopResult<i32, i32>? Or maybe RopResult<i32, String>? Or RopResult<i32, T> for some other type T? That’s right, there’s no way to figure it out from the code.

There’s just not enough information for type inference to understand it. You can either directly specify the type, like so:

let t: RopResult<i32, String> = RopResult::Success(5, None);

Or, maybe, if you use t somewhere later in a way that lets the compiler figure out the type, it will work just as is.


#4

Actually, you can also specify the type of None directly:

let t = RopResult::Success(5, None::<String>);

but the convention is to specify the type of t (correct me if I’m wrong?).


#5

thank you for your clear explanation. Now it is clear to me.
As long as when I use it I specify t there should be no problem.