Rust conditionals: Difference between revisions

From wikinotes
No edit summary
No edit summary
Line 13: Line 13:
</blockquote><!-- if statement -->
</blockquote><!-- if statement -->


= Ternary operator =
<blockquote>
<syntaxhighlight lang="rust">
let weather = if season == "fall" { "lovely" } else { "fine I guess" } // ternary
</syntaxhighlight>
</blockquote><!-- Ternary operator -->


= Pattern Matching =
= Pattern Matching =

Revision as of 14:37, 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
}