Reputation: 545
Can Rust match struct fields? For example, this code:
struct Point {
x: bool,
y: bool,
}
let point = Point { x: false, y: true };
match point {
point.x => println!("x is true"),
point.y => println!("y is true"),
}
Should result in:
y is true
Upvotes: 48
Views: 30048
Reputation: 5216
Can Rust match struct fields?
It is described in the Rust book in the "Destructuring structs" chapter.
match point {
Point { x: true, .. } => println!("x is true"),
Point { y: true, .. } => println!("y is true"),
_ => println!("something else"),
}
Upvotes: 83
Reputation: 430681
The syntax presented in your question doesn't make any sense; it seems that you just want to use a normal if
statement:
if point.x { println!("x is true") }
if point.y { println!("y is true") }
I'd highly recommend re-reading The Rust Programming Language, specifically the chapters on
Once you've read that, it should become clear that point.x
isn't a pattern, so it cannot be used on the left side of a match arm.
Upvotes: 6