Matches syntax issues?

Hi, I am not sure what to search for but I didn't find anything.
I want to check if an enum field equals some parameter
if !matches!(&args[0].0, &vc.script_context.return_type)
but it complains about the first . after vc

error: no rules expected the token `.`
    |         if !matches!(&args[0].0, &vc.script_context.return_type)
    |                                     ^ no rules expected this token in macro call
    |
    = note: while trying to match sequence start

I don't understand why it cannot parse this, it should in my opinion.
So my workaround is to reference vc.script_context.return_type into a variable:

let value_type = &vc.script_context.return_type;
if !matches!(&args[0].0, value_type)

which compiles fine. But it gives me this non-sensical warning:

warning: unused variable: `value_type`
711 |         let value_type = &vc.script_context.return_type;
    |             ^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_value_type`
    |
    = note: `#[warn(unused_variables)]` on by default
warning: unused variable: `value_type`
    |
712 |         if !matches!(&args[0].0, value_type)
    |                                  ^^^^^^^^^^ help: if this is intentional, prefix it with an underscore: `_value_type`

it claims that the variable that I am using here is unused, which is just wrong.
Am I missing something? Or is this a bug?
Thanks in advance

matches! is a shorthand sugar for rust pattern match, it's not something like regex match.

1 Like

The second argument of matches is a pattern, not an expression. It seem like you want == instead.

4 Likes

yes == works, for some reason i thought it does not, I remember errors trying it out, but it does indeed work. Thank you.
I still don't understand why the warning comes up when using matches!. But I have no more problems now.

as already pointed out, matches!() is for rust pattern matching, not for string comparison (Eq) or searching (regex).

do you understand what matches!() macro will expand to? in your example, this line

is equivalent to:

if match &args[0].0 {
    value_type => true,
    _ => false,
}

as you can see, value_type is a "binding "pattern, it will always successfully match the expression, but the variable is not used, so the compiler issues an "unused variable" warning.

3 Likes

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.