rust - Idiomatic way to use a computed value as a pattern in match -
what best way use value computed @ runtime 1 of patterns in match?
i have value (byte
) need match against other values. of values fixed (b'0'..b'9'). others computed @ runtime (c = some_function()
).
my current solution use fake variable , if guard (i.e. k if (k == c)
), not nice me. tried using c
gets interpreted catch-all variable, rather substituted value of c
in context.
the following code snippet shows problem: (also on 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", // <-- had preferred k if (k == c) => "same char", _ => "different char", }; println!("fun({}, {} [{}]) = {}", byte, i, c, msg); }
is idiomatic construct rust can offer?
in short, yes, should use pattern guards this.
to make possible there should way differentiate plain bindings , equality checks. scala, example, based on variable case: if starts capital letter, equality check; otherwise pattern binding. there no such mechanism in rust, no, impossible now.
Comments
Post a Comment