Or Patterns Sharing Field Bindings
Bind the same field from several enum variants in one arm with | patterns, provided every variant gives the binding the same concrete type.
Code
#[derive(Debug)]
enum Event {
SessionStart { session: u32, user: String },
SessionEnd { session: u32, reason: String },
Heartbeat,
}
// 一个分支同时匹配两个变体:session 在两者里都是 u32,绑定类型一致才合法
fn session_of(event: &Event) -> Option<u32> {
match event {
Event::SessionStart { session, .. } | Event::SessionEnd { session, .. } => {
Some(*session)
}
Event::Heartbeat => None,
}
}
fn main() {
let log = [
Event::SessionStart { session: 41, user: String::from("ada") },
Event::Heartbeat,
Event::SessionEnd { session: 41, reason: String::from("idle timeout") },
];
for event in &log {
println!("{:?} -> session {:?}", event, session_of(event));
}
}One arm, two variants, one binding
The arm Event::SessionStart { session, .. } | Event::SessionEnd { session, .. } matches both variants at once and binds session — legal only because session is u32 in each variant, so the shared binding has one concrete type. The .. pattern discards the fields that differ (user, reason), and Some(*session) dereferences once because the match runs on &Event. Event::Heartbeat, which has no session, gets its own arm returning None.
What the demo log prints
SessionStart { session: 41, user: "ada" } -> session Some(41)
Heartbeat -> session None
SessionEnd { session: 41, reason: "idle timeout" } -> session Some(41)
Each line is println!("{:?} -> session {:?}", event, session_of(event)): the derived Debug on the left, the extracted session on the right. Both Session* events carry session 41, so the or-pattern arm resolved them identically while Heartbeat took the None arm.
The line that shares the binding
Event::SessionStart { session, .. } | Event::SessionEnd { session, .. } => {
Some(*session)
}
If the two variants’ session fields had different types, the compiler would reject the arm — the shared binding is the contract this pattern enforces.
Interactive Tools for This Topic
FAQ
- How do you run Or Patterns Sharing Field Bindings?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.