rust-lang / book

The Rust Programming Language

Home Page:https://doc.rust-lang.org/book/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Chapter 18.3 "Matching Named Variables": Missing to add `Ferris` (This code does not produce the desired behavior)

afifurrohman-id opened this issue · comments

{{#rustdoc_include ../listings/ch18-patterns-and-matching/listing-18-11/src/main.rs:here}}

fn main() {
    let x = Some(5);
    let y = 10;

    match x {
        Some(50) => println!("Got 50"),
        Some(y) => println!("Matched, y = {y}"),
        _ => println!("Default case, x = {:?}", x),
    }

    println!("at the end: x = {:?}, y = {y}", x);
}

Hi there! Thanks for opening this issue. The code in the book is correct, actually. It is intentionally designed to be a thing you have to think about a bit to understand, though—because it is there to help you understand how name bindings inside pattern matches work.

In this case, the second branch is the one that matches, because the value of x is not Some(50) but Some(5). The y in that second branch arm is different from the y named with the let y = 10; statement above: it is introducing a new binding named y inside the match block, which shadows the binding outside the block. Hope that helps! Good luck as you keep learning Rust!