Idiomatic way of using the calculated value as a template in a match

What is the best way to use the value computed at runtime as one of the patterns in a match?

I have a value ( byte ) that I need to map to other values. Some of the values ​​are fixed (b'0 '.. b'9'). Others are computed at runtime ( c = some_function() ).

My current solution is to use a fake variable and guard if (i.e. k if (k == c) ), but it doesn't look very good to me. I tried to use only c , but it is interpreted as a catch-all variable, and does not replace the value of c in this context.

The following code snippet shows the problem: ( also in playpen )

 fn main() { fun(b'5', 0); fun(b'C', 0); fun(b'C', 2); } fn fun(byte: u8, i: uint) { let CHARS = b"ABCDEFGH"; let c = CHARS[i]; let msg = match byte { b'0'..b'9' => "numeric", // c => "same char", // <-- I would had preferred this k if (k == c) => "same char", _ => "different char", }; println!("fun({}, {} [{}]) = {}", byte, i, c, msg); } 

Is this the most idiomatic construct Rust can offer?

+5
source share
1 answer

In short, yes, you should use templates for this.

To make it possible, there must be a way to distinguish between simple bindings and equality checks. Scala, for example, does this based on a variable case: if it starts with a capital letter, it is an equality check; otherwise it is a template binding. Rust does not have such a mechanism, so no, now it is not possible.

+4
source

Source: https://habr.com/ru/post/1200604/


All Articles