40

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
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
maku
  • 465
  • 1
  • 4
  • 7
  • 2
    How do you propose this to work with... non-boolean fields? For example, how would this work with a `struct Person { surname: String, age: u8 }`? – Matthieu M. Dec 30 '16 at 10:11

2 Answers2

71

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"),
}
koral
  • 525
  • 7
  • 23
aSpex
  • 4,790
  • 14
  • 25
5

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.

koral
  • 525
  • 7
  • 23
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 2
    Most functional programming languages have such features, it's actually extremely useful to avoid having nested if/else as regular low-level languages that do not have pattern-matching would require... so, I recommend you to read about pattern-matching :D – Marcelo Boeira Apr 29 '21 at 19:07
  • @MarceloBoeira I’m quite familiar with Rust’s pattern matching. You’ll note that I’ve linked to two specific pieces of documentation covering them. The OPs request isn’t about pattern matching as expressed in Rust. They haven’t even expressed what should happen when both fields are true. – Shepmaster Apr 29 '21 at 19:24