0

Consider the following code.

struct MyStruct {
    char0: char,
    char1: char,
}

impl MyStruct {
    fn swap(&self, input: char) -> Option<char> {
        if input == self.char0 {
            Some(self.char1)
        } else if input == self.char1 {
            Some(self.char0)
        } else {
            None
        }
    }

    fn swap2(&self, input: char) -> Option<char> {
        match input {
            self.char0 => Some(self.char1),
            self.char1 => Some(self.char0),
            _ => None
        }
    }
}

fn main() {
    let instance = MyStruct {
        char0: 'A',
        char1: 'B',
    };
    assert_eq!(instance.swap('A'), Some('B'));
}


It will compile and run correctly when I remove swap2. It will however produce a compile time error when I add swap2. The error is:

error: expected one of `!`, `(`, `...`, `..=`, `..`, `::`, `=>`, `if`, `{`, or `|`, found `.`
  --> src/main.rs:19:17
   |
19 |             self.char0 => Some(self.char1),
   |                 ^ expected one of 10 possible tokens

IMO both functions should be equivalent, but the compiler won't let me use match to compare a variable against a field of an instance. Why is that?

I'm running rustc 1.60.0.

sarema
  • 695
  • 5
  • 18
  • 1
    You cannot match with variables at all, only constants and literals. Use a [match guard](https://doc.rust-lang.org/rust-by-example/flow_control/match/guard.html) if you want to use a `match`. – kmdreko May 13 '22 at 17:24
  • 1
    This question was closed before I could post my explanation, but essentially `match` is meant for pattern matching while if-else is meant for value-to-value comparison. You can read more about pattern matching [here](https://doc.rust-lang.org/book/ch18-00-patterns.html). – Ian S. May 13 '22 at 17:29

0 Answers0