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
.