ferrous-systems / rust-training

Learning materials for the Rust Training courses by Ferrous Systems
127 stars 16 forks source link

Struct pattern matching #137

Open jonathanpallant opened 4 months ago

jonathanpallant commented 4 months ago

Building on https://github.com/ferrous-systems/rust-training/issues/103, we should perhaps explain pattern matching when the data contained in an enum variant is a struct.

enum Reason {
   Finished,
   Failed
}

enum Action {
   Send,
   Receive
}   

enum Message {
    Start,
    Process(Action),
    End { reason: Reason, timeout: u32 }
}

match message {
    Message::Start => { /* pattern has no parameters */ }
    Message::Process(Action::Send) => { /* two patterns in one */ }
    Message::Process(a) => { /* grab the action as `a` */ }
    Message::End { reason, timeout } => { /* must match field names */ }
}
jonathanpallant commented 4 months ago

Although I note the book doesn't cover this syntax.