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. 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. In other words, instead of assigning "23456" as per my example, I want to assign the actual random number being tested in the match. 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With