book icon indicating copy to clipboard operation
book copied to clipboard

Chapter 18.3 "Matching Named Variables": Better Illustrate the point in the Example Listing

Open Jomich opened this issue 3 years ago • 0 comments

  • [X] I have checked the latest main branch to see if this has already been fixed
  • [X] I have searched existing issues and pull requests for duplicates

URL to the section(s) of the book with this problem:

https://doc.rust-lang.org/stable/book/ch18-03-pattern-syntax.html#matching-named-variables

Description of the problem:

This section presents how named variables in patterns can shadow outer variables. However the paragraph "If x had been a None value instead of Some(5), ..." talks about variable x which is never shadowed in the example listing.

I feel that the phrasing of this paragraph makes what is happening unclear at first read.

Suggested fix:

This can go two ways:

  1. As the listing name suggests, the example should be about how the variable y is shadowed but only in the arm where it is matched. Thus change the paragraph to mention variable y and change the listing to:
//...
// Prints "Matched, y = 5" for x = Some(5)
// Prints "Default case, y = 10" for x = None
match x {
    Some(50) => println!("Got 50"),
    Some(y) => println!("Matched, y = {:?}", y),
    _ => println!("Default case, y = {:?}", y),
}
//...

I feel that this would make it clearer what happens with the shadowing

  1. It might also be interesting to show that the matched variable x itself can be shadowed in an arm:
//...
// Prints "Matched, x = 5" for x = Some(5)
// Prints "Default case, x = None" for x = None
match x {
    Some(50) => println!("Got 50"),
    Some(x) => println!("Matched, x = {:?}", x),
    _ => println!("Default case, x = {:?}", x),
}
//...

Jomich avatar Feb 11 '22 14:02 Jomich