0

I'm trying to match a struct containing String members. I found this will make me confusing below, how can I operate to avoid it? I kown using if...else... could solve the problem, how can I use match to make sense?

#[derive(Debug, PartialEq)]
struct UserData{
    name: String,
    id: u64,
}

fn some_test(){
    let mud2 = UserData{
        name: String::from("name two"),
        id: 77,
    };

    let name_string = String::from("name one");

    //***attention: the name_string below is regarded as a new variables, so the first arm will match any value of a UserData
    match mud2{
        //It's something may confuse!!!
        UserData{name: name_string, id} => println!("{}", id),
        UserData{name, id: 77} => println!("{}", name),
        UserData{name, id} => println!("{}-{}", name, id),
    }
}
Herohtar
  • 5,347
  • 4
  • 31
  • 41
xeeyu
  • 13
  • 3
  • 2
    Does this answer your question? [How do I match a String in a struct with a constant value?](https://stackoverflow.com/questions/29048833/how-do-i-match-a-string-in-a-struct-with-a-constant-value) (not 100% the same as it's not static here but it's the same problem) – Denys Séguret Oct 11 '21 at 07:18

1 Answers1

2

This is the perfect use case for a match guard:

match mud2{
    UserData{name, id} if name == name_string => println!("{}", id),
    UserData{name, id: 77} => println!("{}", name),
    UserData{name, id} => println!("{}-{}", name, id),
}
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758