Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

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
};
like image 899
Brian Oh Avatar asked Feb 14 '23 19:02

Brian Oh


1 Answers

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
like image 121
Matthew Mcveigh Avatar answered Jun 07 '23 14:06

Matthew Mcveigh