book
book copied to clipboard
Chapter 18.3 "Matching Named Variables": Better Illustrate the point in the Example Listing
- [X] I have checked the latest
mainbranch 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:
- As the listing name suggests, the example should be about how the variable
yis shadowed but only in the arm where it is matched. Thus change the paragraph to mention variableyand 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
- It might also be interesting to show that the matched variable
xitself 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),
}
//...