Type ascription in patterns

Why is the following not allowed? Where should I put the type ascription to help the compiler?

if let Err(e: io::Error) = <expr> {
    ...
}

You should be able to do this for io::Error:

if let Err(e @ io::Error { .. }) = <expr> {
}

The problem with that is the innability to capture the whole the io::Error. That only allows you to capture fields of the io::Error. It also doesn't work with types that have no fields.

That captures the whole io::Error. If you want something without fields, use e @ Foo or if you have unnamed fields (tuple types), e @ Foo(..) (but e @ Foo { .. } also works for fieldless and unnamed fields types)

But not for primitives such as usize

Why do you need it for a primitive? I think generalized type ascription could solve this:

When I have a Result<T, E> and E is a primitive but the compiler doesn't know it. I encountered this while playing with try blocks which don't have very good type determining yet.

Thanks for the link that does look like it would fix it and what I tried to do initially.

You can specify usize in the pattern like this:

    if let Result::Err::<_, usize>(a) = <expr> {
        println!("usize: {}", a)
    }
3 Likes