Confusions about values of 'Enum'


#1

A value of an enum type contains information about which variant it is, in addition to any data associated with that variant. This is sometimes referred to as a ‘tagged union’, since the data includes a ‘tag’ indicating what type it is. The compiler uses this information to enforce that you’re accessing the data in the enum safely. For instance, you can’t simply try to destructure a value as if it were one of the possible variants:
fn process_color_change(msg: Message) {
let Message::ChangeColor(r, g, b) = msg; // compile-time error
}
https://doc.rust-lang.org/stable/book/enums.html

These are words in rust book of enums chapter. I have some question about this.

  1. what’s the compile-time error?
    I write a code, and it can work.
fn main() {
    // the code from the book.
    fn process_color_change(msg: Message) {
        let Message::ChangeColor(r, g, b) = msg; // compile-time error
    }
    
    enum Message {
        ChangeColor(i32, i32, i32),
    }
    let m = Message::ChangeColor(3, 4, 5);
    process_color_change(m);
}

There is no error. I must have misunderstood something , what is it?
Any one can explain it for me, many thanks!

2 . What exactly is the value of an enum?
From these words above,the value of an enum = variant + data
In the next chapter of ‘match’, the form of match branch is like 'val => expression'.

fn process_message(msg: Message) {
        match msg {         
            Message::ChangeColor(r, g, b) => println!("good job"),
        }
    }

Isn’t the 'value’ on the left side of => above just a ‘variant type’ ? I think it lacks ‘data’.
but Message::ChangeColor(3, 4, 5) => println!("{}") has error.

error: non-exhaustive patterns: `ChangeColor(_, _, _)` not covered [E0004]

So the ‘match’ can’t match ‘value’?
I find that I can’t understand the book very well. Is there any advice?:disappointed:


#2

Because you changed the definition of Message. The correct definition is at the top of the chapter. Your code works because your Message has only one variant, thus a value of type Message will always be a Message::ChangeColor, thus the assignment works.

No, it’s a pattern. Specifically, a pattern that matches any Message::ChangeColor, binding the three values contained within to names r, g, and b.

Because that pattern will only match when the three values are exactly 3, 4, and 5. What if they’re 2, 5, and 248921? It’s telling you that there are patterns of data your match does not account for, and the compiler must be able to prove all match expressions are exhaustive: that is, that they cover all possible patterns.


#3

Got it,thanks,your reply is so helpful and understandable.:grin: