Rust conditionals: Difference between revisions
From wikinotes
Line 43: | Line 43: | ||
1 | 3 | 5 => "one three or five", | 1 | 3 | 5 => "one three or five", | ||
_ => "something else" | _ => "something else" | ||
} | |||
</syntaxhighlight> | |||
When matching a parametrized enum, you can access the tuple/struct/value that is bound to it | |||
<syntaxhighlight lang="rust"> | |||
enum Pet { | |||
Cat(String, u8), | |||
Dog{name: String, age: u8}, | |||
Lizard(u8), | |||
} | |||
let pet = Pet::Lizard(5); | |||
match pet { | |||
Cat(name, age) => { format!("cat, name={}, age={}", name, age) }, | |||
Dog(dog) => { format!("dog, name={dog.name}, age={dog.age}") }, | |||
Lizard(age) => { format!("lizard, age={}", age) } | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Pattern Matching --> | </blockquote><!-- Pattern Matching --> |
Revision as of 21:56, 7 February 2023
if statement
if num < 5 { // .. } else if { // .. } else { // .. }
Ternary operator
let weather = if season == "fall" { "lovely" } else { "fine I guess" } // ternary
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 }You can match multiple values
let result = match num { 1 | 3 | 5 => "one three or five", _ => "something else" }When matching a parametrized enum, you can access the tuple/struct/value that is bound to it
enum Pet { Cat(String, u8), Dog{name: String, age: u8}, Lizard(u8), } let pet = Pet::Lizard(5); match pet { Cat(name, age) => { format!("cat, name={}, age={}", name, age) }, Dog(dog) => { format!("dog, name={dog.name}, age={dog.age}") }, Lizard(age) => { format!("lizard, age={}", age) } }