Rust conditionals: Difference between revisions
From wikinotes
(Created page with " = Pattern Matching = <blockquote> Like a switch statement,<br> but the compiler ensures the entire valid range of items is checked for.<br> especially useful for enums. <syntaxhighlight lang="rust"> // if num is '1', returns 'a' // if num is >2, returns 'c' let result = match num { 1 => "a", 2 => "b", _ => "c", } </syntaxhighlight> </blockquote><!-- Pattern Matching -->") |
|||
Line 6: | Line 6: | ||
especially useful for enums. | especially useful for enums. | ||
In the following case, if <code>_</code> was omitted<br> | |||
you'd need to ensure the full range of possible i32 numbers were supported!. | |||
<syntaxhighlight lang="rust"> | <syntaxhighlight lang="rust"> | ||
// if num is '1', returns 'a' | // if num is '1', returns 'a' | ||
Line 12: | Line 14: | ||
1 => "a", | 1 => "a", | ||
2 => "b", | 2 => "b", | ||
_ => "c", | _ => "c", // anything other than 1 or 2 | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Pattern Matching --> | </blockquote><!-- Pattern Matching --> |
Revision as of 23:28, 6 February 2023
Pattern Matching
Like a switch statement,
but the compiler ensures the entire valid range of items is checked for.
especially useful for enums.In the following case, if
_
was omitted
you'd need to ensure the full range of possible i32 numbers were supported!.// if num is '1', returns 'a' // if num is >2, returns 'c' let result = match num { 1 => "a", 2 => "b", _ => "c", // anything other than 1 or 2 }