How to match member or field inside struct?

The code won't compile and show that expected one of `!`, `(`, `...`, `..=`, `..`, `::`, `=>`, `if`, `{`, or `|`, found `.` in self.one .

struct Number{
    one:i8,
    two:i8,
}

impl Number{
    fn mat(&self, x: i8){
        match x{
            self.one =>{
                println!("{}", x),
            },
            self.two => {
                println!("{}", x),
            },
            _ =>{
                println!("_"),
            }
        }
    }
}

fn main() {
    let n = Number{
        one:1,
        two:2,
    };
    n.mat(3);
}

this should be a pattern , try this

_ if self.one == x

If I've worked out what you're trying to do correctly, you may be looking for something like:

impl Number {
    fn mat(&self, x: i8) {
        match self {
            Self { one, .. } if x == *one => println!("{}", x),
            Self { two, .. } if x == *two => println!("{}", x),
            _ => println!("_"),
        }
    }
}

Does it means that I can not use match in struct methods with it's field?

Thanks for you! But do you know why it could't match inside struct like self.one without deconstructing?

a pattern requires that all part of it are compile time value, in your case , it's a runtime value

When running a match, constants are compared against but variables are bound to. So if you attempt to match "x", it'll bind a value to a new variable "x" instead of running a comparison. Bringing that value out into a guard allows us to compare it against something at runtime.

I got it, thanks!

I got it :+1:

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.