Book: Catch-all match arm variable used without explanation

Created on 19 Mar 2019  路  3Comments  路  Source: rust-lang/book

Chapter 6.2, at the end, does discuss the _ placeholder pattern. However it makes it sound super special, as opposed to just being an unused variable. No mention that you can use an arbitrary variable name to capture the value.

Then in chapter 9.2 in listing 9-5 the catch-all is used again but with a named variable other_error.

match error.kind() {
    ErrorKind::NotFound => match File::create("hello.txt") {
        Ok(fc) => fc,
        Err(e) => panic!("Tried to create file but there was a problem: {:?}", e),
    },
    other_error => panic!("There was a problem opening the file: {:?}", other_error),
},

The only explanation given is _The last arm of the outer match stays the same so the program panics on any error besides the missing file error._ It claims that the last arm stays the same, but that arm pattern is Err(error) in the previous listing (9-4). So while the functionality might be the same, the match arm pattern definitely isn't.

When I got to this as I was originally reading the book, this situation confused me. I was wondering if this is a special error matching generic or something. After some playing around with code I figured out you can just use arbitrary variables as the catch-all arm.

I think this situation could be greatly improved with just a minor note either in chapter 6.2 near the _ placeholder pattern to say that you can actually capture the value and use it. Or a similar description near listing 9-5, instead of the claim that the last arm stays the same.

Enhancement

Most helpful comment

I agree! I understand this for the first time now that I have read your post! Definitely something which can be improved.

All 3 comments

I agree! I understand this for the first time now that I have read your post! Definitely something which can be improved.

I agree!

I'm now reading Chapter 9.2 and find other_err confusing. So I google it and find this issue. Gladly I'm not the only one that gets confused here but sadly this part of The Book is so confusing!

I agree, and is also find confusing this part: "The () is just the unit value, so nothing will happen in the _ case". The unit value was not properly explained before, and the sentence let me think that () work always (instead, it work for String but not for other types, such float)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

binarycrusader picture binarycrusader  路  4Comments

ahowlett1965 picture ahowlett1965  路  5Comments

serialhex picture serialhex  路  4Comments

carols10cents picture carols10cents  路  5Comments

icanrealizeum picture icanrealizeum  路  3Comments