Tiago
Tiago

Reputation: 3131

Pattern matching a struct with a String

Is it possible to pattern match a String field? I can't make this code work.

struct Foo {
    x: int,
    y: int,
    str: String
}

pub fn main() {
    let a = Foo { x: 1, y: 2 , str: "Hi".to_string()};
    match a {
        Foo { x: x, y: y, str: "Hi".to_string() } => println!("Found {}, {}", x, y),
        _ => {}
    }
}

Gives this error:

<anon>:10:36: 10:37 error: expected one of `,` or `...`, found `.`
<anon>:10         Foo { x: x, y: y, str: "Hi".to_string() } => println!("Found {}, {}", x, y),
                                             ^

Upvotes: 1

Views: 170

Answers (1)

wingedsubmariner
wingedsubmariner

Reputation: 13667

match cases may not contain expressions like "Hi".to_string(), only constants (e.g. 3, "Hi") or variables (e.g. x). To match on a String field you will need to use pattern guards:

match a {
    Foo { x: x, y: y, str: ref str } if str == &"Hi" =>
        println!("Found {}, {}", x, y),
    _ => {}
}

The if str == &"Hi" is the pattern guard to check the value of the String. Note that the pattern guard forces us to use ref to capture a reference to the String, rather than moving it out of the struct.

Upvotes: 6

Related Questions