-1

I'm totally new to Rust and in the early steps of learning the language.

As such, I'm reading The book while also following along the examples in Rust by Example, and I came across some behavior that puzzles me and I would hope to get an explanation for.


The chapter 3.2.1 has the following example code:

enum Status {
    Rich,
    Poor,
}

fn main() {
    use crate::Status::{Poor, Rich};
    let status = Poor;

    match status {
        // Note the lack of scoping because of the explicit `use` above.
        Rich => println!("The rich have lots of money!"),
        Poor => println!("The poor have no money..."),
    }
}

which, as expected, returns:

The poor have no money...

However, I was experimenting a bit and altered the code to:

enum Status {
    Rich,
    Poor,
}

fn main() {
    use crate::Status::Poor;
    let status = Poor;

    match status {
        // Note the lack of scoping because of the explicit `use` above.
        Rich => println!("The rich have lots of money!"),
        Poor => println!("The poor have no money..."),
    }
}

I was half-expecting a compile-error, but what I didn't understand is, why that code gives me:

The rich have lots of money!

Can somebody explain to me, what is going on here?

BmyGuest
  • 6,331
  • 1
  • 21
  • 35
  • 1
    Read the compiler warnings… – mcarton Jun 18 '20 at 21:14
  • @mcarton Well, I ran the code on [the page it came from](https://doc.rust-lang.org/stable/rust-by-example/custom_types/enum/enum_use.html) and it didn't give any compiler warnings. I guess they are turned off there... – BmyGuest Jun 18 '20 at 21:34
  • Your altered code does have warnings though. – mcarton Jun 18 '20 at 22:41
  • @mcarton You misunderstood. The code does have warnings (which are helpful) when compiled form the command line. However, I was using the in-browser run of the "Rust by example" site which apparently has switched compiler warnings off (it shows compiler errors). That's why I missed it. – BmyGuest Jun 19 '20 at 06:35
  • 1
    This is a case where an IDE can also makes it easier to spot the issue. IntelliJ IDEA, for example, uses a different typeface and color for enum variant names vs. variables, so `Rich` and `Poor` would have looked different from each other in that pattern. – Brent Kerby Jun 19 '20 at 23:28

1 Answers1

3

Since you didn't specified Status::Rich it is taking it as a "match any and assign to Rich", the second match is basically unreachable since the first one will match everything.

Think of it, as a variable named Rich instead of the enum.

#[derive(Debug)]
enum Status {
    Rich,
    Poor,
}

fn main() {
    use crate::Status::Poor;
    let status = Poor;

    match status {
        matched_status => println!("the status matched was {:?}", matched_status),
        Poor => unreachable!()
    }
}
Julio Daniel Reyes
  • 5,489
  • 1
  • 19
  • 23