使用计算值作为匹配模式的惯用方法 [英] Idiomatic way to use a computed value as a pattern in match
问题描述
使用在运行时计算的值作为匹配模式之一的最佳方法是什么?
What is the best way to use a value computed at runtime as one of the patterns in a match?
我有一个值 (byte
),我需要与其他值匹配.一些值是固定的(b'0'..b'9').其他在运行时计算(c = some_function()
).
I have a value (byte
) that I need to match against other values. Some of the values are fixed (b'0'..b'9'). Others are computed at runtime (c = some_function()
).
我目前的解决方案是使用一个假变量和一个 if 守卫(即 k if (k == c)
),但对我来说它看起来不太好.我尝试只使用 c
但这被解释为一个包罗万象的变量,而不是在该上下文中替换 c
的值.
My current solution is to use a fake variable and a if guard (i.e. k if (k == c)
), but it does not look very nice to me. I tried using just c
but that gets interpreted as a catch-all variable, rather than substituted for the value of c
in that context.
以下代码片段显示了问题:(也在游戏围栏上)
The following code snippet shows the 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", // <-- I would had preferred this
k if (k == c) => "same char",
_ => "different char",
};
println!("fun({}, {} [{}]) = {}", byte, i, c, msg);
}
这是 Rust 可以提供的最惯用的构造吗?
Is this the most idiomatic construct that Rust can offer?
推荐答案
简而言之,是的,您应该为此使用模式保护.
In short, yes, you should use pattern guards for this.
为了使其成为可能,应该有一种方法来区分普通绑定和相等性检查.例如,Scala 是基于可变大小写的:如果以大写字母开头,则是相等性检查;否则就是模式绑定.Rust 中没有这样的机制,所以不,现在不可能了.
To make it possible there should be a way to differentiate plain bindings and equality checks. Scala, for example, does this based on variable case: if it starts with capital letter, it is an equality check; otherwise it is a pattern binding. There is no such mechanism in Rust, so no, it is impossible now.
这篇关于使用计算值作为匹配模式的惯用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!