Matches! macro and enum

Hi all,

I'm trying to use the matches! macro to test an enum arm:

enum CallbackType {
    Script(Option<String>),
    Tcp(Option<String>),
    Domain(Option<String>),
}
fn main() {
    let a = CallbackType::Script(Some(String::from("foo")));
    let a_s = String::from("foo");
    assert!(matches!(a, CallbackType::Script(Some(foo))));
}

but it seems the compiler doesn't care about the variable:

warning: unused variable: `foo`
 --> src/main.rs:9:51
  |
9 |     assert!(matches!(a, CallbackType::Script(Some(foo))));
  |                                                   ^^^ help: if this is intentional, prefix it with an underscore: `_foo`

How can I test the enum matches the right leg and it's value is matching the value inside the enum ?

Thanks a lot for your help.

The macro, like match supports if guards, so one option is something like this:

fn main() {
    let a = CallbackType::Script(Some(String::from("foo")));
    let a_s = String::from("foo");
    assert!(matches!(a, CallbackType::Script(Some(foo)) if foo == a_s));
}
1 Like

@scottmcm Thanks a lot, works perfectly !

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.