Match - Rust by Example

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

match - Rust By Example 09.10.

2023 13:05

match
Rust provides pattern matching via the match keyword, which can be used like a C
switch . The first matching arm is evaluated and all possible values must be covered.

1 fn main() {
2 let number = 13;
3 // TODO ^ Try different values for `number`
4
5 println!("Tell me about {}", number);
6 match number {
7 // Match a single value
8 1 => println!("One!"),
9 // Match several values
10 2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
11 // TODO ^ Try adding 13 to the list of prime values
12 // Match an inclusive range
13 13..=19 => println!("A teen"),
14 // Handle the rest of cases
15 _ => println!("Ain't special"),
16 // TODO ^ Try commenting out this catch-all arm
17 }
18
19 let boolean = true;
20 // Match is an expression too
21 let binary = match boolean {
22 // The arms of a match must cover all the possible values
23 false => 0,
24 true => 1,
25 // TODO ^ Try commenting out one of these arms
26 };
27
28 println!("{} -> {}", boolean, binary);
29 }

https://doc.rust-lang.org/rust-by-example/flow_control/match.html Stránka 1 z 1

You might also like