简体   繁体   English

如何使用Rust我将匹配的值分配为结果?

[英]How using Rust do I assign the value being matched as the result?

I've used "match" a little in Rust, and I've searched for a solution to this problem, because I'm sure there must be a solution. 我在Rust中使用了“匹配”,我已经搜索了这个问题的解决方案,因为我确信必须有一个解决方案。 In the following example, in the case where the random number generated is not zero, I want the random-number generated to be assigned to the variable i_bal. 在以下示例中,在生成的随机数不为零的情况下,我希望将生成的随机数分配给变量i_bal。 In other words, instead of assigning "23456" as per my example, I want to assign the actual random number being tested in the match. 换句话说,我不是根据我的例子分配“23456”,而是想在匹配中分配正在测试的实际随机数。 I know that there may be better ways of solving this, however, I'd like to know the solution using this method. 我知道可能有更好的方法来解决这个问题,但是,我想知道使用这种方法的解决方案。

Example : 示例:

let i_bal: i64 = match std::rand::task_rng().gen() {
    0 => 1234,
    _  => 23456
};

Instead of the wildcard pattern you can use the variable pattern. 您可以使用变量模式代替通配符模式。 They both match everything, but with the variable pattern the matched value is bound to the name: 它们都匹配所有内容,但是使用变量模式,匹配的值绑定到名称:

let i_bal: i64 = match std::rand::task_rng().gen() {
    0 => 1234,
    x => x
};

Why in some cases you'd want to use the wildcard pattern is so that you make it clear you don't need the value, and so that you don't have to pollute the scope with unnecessary variable names 为什么在某些情况下,您希望使用通配符模式,以便明确表示您不需要该值,因此您不必使用不必要的变量名称污染范围

For example if you had a tuple of (high, low, open, close), and only wanted the variables high and low from it you could do: 例如,如果你有一个(高,低,开,关)元组,并且只想要变量的高和低,你可以这样做:

let (high, low, _, _) = tickerData

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM