0

Rust – Switch Statements Examples Using Match

Rust does not have a switch  keyword but has match  construct that works like a switch statement. Generally, match can run codes or return a single value. It cannot do both at the same time.

Run Codes with Match

Here we have a few functions that are called based on user_choice .

Output

The function f_unknown()  is run because there is no 10 matching. We are using _  as a catch-all condition.

Return Value from Match

Instead of running codes, match  can return values.

Output

Other Examples

Using String and &Str

Output

Using enum

Output

References

https://doc.rust-lang.org/rust-by-example/flow_control/match.html

Karl San Gabriel

Karl San Gabriel

Professional Software Developer