How could error.kind() match an arm being randomly named?

Err(error) => match error.kind() {
    ErrorKind::NotFound => match File::create("file.txt") {
        Ok(fc) => {
            println!("Creating file.txt");
            fc
        },
        Err(e) => panic!("Problem creating file.txt: {:?}", e),
    },
    random_name => {
        panic!("Problem cannot open file.txt: {:?}", random_name);
    } 
}

In this code, we have this random_name. How could a name fabricated by me stay here? What error.kind() can match here?
Thanks.

It's a valid pattern -- in fact you have used this a lot already, when writing things like

let random_name = ...

In this case, random_name will be bound to any value at all -- anything that error.kind() returned that wasn't an ErrorKind::NotFound (as that would be caught by the first arm in the match).

If you're familiar with catch-all match arms:

match error.kind() {
    ErrorKind::NotFound => { /* ... */ }
    _ => {} // <-- like this
}

random_name does pretty much the same thing, except the value being matched against is bound to random_name (so you can e.g. put it into your panic message within the arm).

2 Likes

Thanks!

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.