Type hint for if let binding?


#1

I thought let pattern: type works everywhere, but apparently it doesn’t in if let. Is my syntax wrong, or was I imagining this?

fn main() {
    let Ok(a): Result<u32,_> = "1".parse(); // ignoring that it doesn't cover Err
    
    match "1".parse() {
        Ok(a): Result<u32,_> => {}
    }
    
    if let Ok(a): Result<u32,_> = "1".parse() {   
    }
}

#2

Nope, it doesn’t look like patterns support type ascription at all. RFC 803 says

An earlier version of this RFC covered type ascription in patterns too, that has been postponed

There’s a little bit of discussion in RFC issue 354, but this seems like a good example of why having full support for type ascription in patterns could be very useful. I would even go so far as to hope this could be written as

match "1".parse() {
    Ok(a: u32) => {}
}

if let Ok(a: u32) = "1".parse() {
}

since the Result type can be inferred from the parse definition, then the Error type can be inferred through the resulting associated type in the FromStr implementation.


The currently unstable type ascription allows for writing this as

#![feature(type_ascription)]
if let Ok(a) = "1".parse(): Result<u32, _> {   
}

But I really don’t find that as nice a form, especially when the turbo-fish version is shorter

if let Ok(a) = "1".parse::<u32>() {
}