Rust Programming: Catch-all Patterns and the _ Placeholder

0

The `_` placeholder is a special pattern in Rust that matches any value and does not bind to that value. This tells Rust we aren't going to use the value, so Rust won't warn us about an unused variable. For example, the following code uses the `_` placeholder to match any value other than 3 or 7:

let dice_roll = 9;

match dice_roll {

    3 => add_fancy_hat(),

    7 => remove_fancy_hat(),

    _ => reroll(),

}

In this case, the `_` placeholder will match the value 9, and the `reroll()` function will be called.

The `_` placeholder can also be used to explicitly ignore all other values that don't match a pattern in an earlier arm. For example, the following code uses the `_` placeholder to indicate that nothing else happens on your turn if you roll anything other than a 3 or a 7:

let dice_roll = 9;

match dice_roll {

    3 => add_fancy_hat(),

    7 => remove_fancy_hat(),

    _ => (),

}

In this case, the `()` unit value is used to indicate that no code should be executed.

Post a Comment

0Comments
Post a Comment (0)