0

For example in Elixir's case statement, the following code is valid and will match 10 to 1:

x = 1
case 10 do
    ^x -> "Won't match"
    _ -> "Will match"
end

In Rust however, ^ is not a valid operator for this use case. It just gives an error that says something like "expected pattern, found ^". I have tried doing this:

let x = 1;
match 10 {
    x => "Won't match",
    _ => "Will match",
}

But it binds 10 to x and returns "Won't match" (it is equivalent to "x @ _"). Is there a way to dynamically include x so that whatever x is, it will match against its value? (Note: I realize I can just use an if statement but I'm curious if the match statement provides a solution)

GiraffeKey
  • 23
  • 3
  • For those of us who aren't familiar with Elixir, what is `^` supposed to do there? – trent Sep 25 '20 at 19:26
  • I believe that without it, it will bind a value to x, similar to Rust. It allows you to insert the value of x, defined above the case statement, into the pattern. – GiraffeKey Sep 27 '20 at 02:45

1 Answers1

5

You can use a match arm guard for this scenario. Bind the match literal to some other variable, say y, and then check y == x in the guard. Example:

fn main() {
    let x = 1;
    let result = match 10 {
        y if y == x => "10 matched x value",
        _ => "10 didn't match x value",
    };
    println!("{}", result); // 10 didn't match x value
}

playground

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98