Skip to content

Commit f411d44

Browse files
committed
tested 17 different matching patterns
1 parent e8140db commit f411d44

File tree

1 file changed

+214
-6
lines changed

1 file changed

+214
-6
lines changed

c18_pattern_matching/src/main.rs

Lines changed: 214 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
1+
fn print_coordinates(&(x,y): &(i32, i32)){
2+
println!("Current location: ({}, {})", x,y);
3+
4+
}
15
fn main() {
6+
println!("1) Increment x by 1 if it is not None!");
27
let mut x = Some(1);
38
//let mut x: Option<i32> = None;
4-
println!("i={:?}", x);
9+
println!("x={:?}", x);
510
//let x = ();
611
x = match x {
712
None => None,
813
Some(i) => Some(i + 1),
914
};
10-
println!("i={:?}", x);
11-
12-
println!("Hello, world!");
15+
println!("x={:?}", x);
1316

17+
println!("2) Determine the BG color according to many conditions via if let.");
1418
let favorite_color: Option<&str> = None;
1519
let is_tuesday = false;
1620
let age: Result<u8, _> = "34".parse();
@@ -21,11 +25,215 @@ fn main() {
2125
println!("Tuesday is green day!");
2226
} else if let Ok(age) = age {
2327
if age > 30 {
24-
println!("Using purple as the background color");
28+
println!("Using purple as the background color as age>30");
2529
} else {
26-
println!("Using orange as the background color");
30+
println!("Using orange as the background color as age<=30");
2731
}
2832
} else {
2933
println!("Using blue as the background color");
3034
}
35+
36+
println!("3) while let pattern.");
37+
let mut stack = Vec::new();
38+
stack.push(1);
39+
stack.push(2);
40+
stack.push(3);
41+
while let Some(top) = stack.pop(){
42+
println!("{}", top);
43+
}
44+
45+
println!("4) for loops");
46+
let v = vec!['a', 'b', 'c'];
47+
for (index, value) in v.iter().enumerate(){
48+
println!("Value {value} at index {index}");
49+
}
50+
51+
println!("5) Patterns in function parameters");
52+
let point = (3,5);
53+
print_coordinates(&point);
54+
55+
// refutable pattern disallowed with let.
56+
//let Some(x) = Some(10);
57+
58+
println!("6) Matching literal patterns");
59+
let x =1;
60+
match x{
61+
1 => println!("one"),
62+
2 => println!("two"),
63+
3 => println!("three"),
64+
_ => println!("anything"),
65+
}
66+
67+
println!("7) Matching named variables");
68+
let x = Some(5);
69+
let y = 10;
70+
match x {
71+
Some(50) => println!("Got 50"),
72+
Some(y) => println!("Matched, y={y}"),
73+
_ => println!("Default case, x = {:?}", x),
74+
}
75+
println!("At the end: x={:?}, y={y}", x);
76+
77+
println!("8) Multiple patterns");
78+
let x = 2;
79+
match x{
80+
1 | 2 => println!("One or two"),
81+
3 => println!("three"),
82+
_ => println!("anything"),
83+
}
84+
85+
println!("9) Matching ranges of values with ..=");
86+
let x = 1;
87+
match x {
88+
1..=5 => println!("One through five"),
89+
_ => println!("something else"),
90+
}
91+
92+
let x = 'c';
93+
match x {
94+
'a'..='j' => println!("an early ASCII letter"),
95+
'k'..='z' => println!("a late ASCII letter"),
96+
_ => println!("something else"),
97+
98+
}
99+
100+
println!("10) De-structure structs");
101+
struct Point{
102+
x:i32,
103+
y:i32,
104+
z:i32,
105+
}
106+
let p = Point{x:0, y:7, z:-1};
107+
let Point {x:a, y:b, z:c} = p;
108+
assert_eq!(a, 0);
109+
assert_eq!(7, b);
110+
assert_eq!(-1, c);
111+
112+
assert!(a==0);
113+
114+
//shorthand form
115+
let Point {x, y, z} = p;
116+
assert_eq!(x, 0);
117+
assert_eq!(7, y);
118+
assert_eq!(z, -1);
119+
assert!(x==0);
120+
121+
println!("10.1) De-structure structs with literal values");
122+
match p {
123+
Point{x, y:0, z:-1} => println!("One the x axis is {x}"),
124+
Point{x:0, y, z} => println!("One the y axis is {y}"),
125+
Point{x, y, z} => {
126+
println!("On neighter axis: ({x}, {y}, {z})");
127+
}
128+
}
129+
130+
println!("11) De-structure enums");
131+
132+
enum Message{
133+
Quit,
134+
Move {x:i32, y:i32},
135+
Write(String),
136+
ChangeColor(i32, i32, i32),
137+
}
138+
let msg = Message::ChangeColor(0, 160 , 255);
139+
match msg {
140+
Message::Quit => {
141+
println!("The Quit variant has no data to destructure");
142+
}
143+
Message::Move { x, y } => {
144+
println!("Move in the x direction {x} and in the y direction {y}");
145+
}
146+
Message::Write(text) => {
147+
println!("Text message: {text}");
148+
}
149+
Message::ChangeColor(r, g, b) => {
150+
println!("Change the color to red {r}, greeen {g}, and blue {b}");
151+
}
152+
153+
}
154+
155+
println!("12) De-structure nexted structs and enums");
156+
enum Color {
157+
Rgb(i32, i32, i32),
158+
Hsv(i32, i32, i32),
159+
}
160+
enum Message2{
161+
Quit,
162+
Move {x:i32, y:i32},
163+
Write(String),
164+
ChangeColor(Color),
165+
}
166+
167+
let msg = Message2::ChangeColor(Color::Hsv(0, 160 , 255));
168+
match msg {
169+
Message2::ChangeColor(Color::Rgb(r,g,b)) => {
170+
println!("Change the color to red {r}, greeen {g}, and blue {b}");
171+
}
172+
Message2::ChangeColor(Color::Hsv(h, s, v)) => {
173+
println!("Change the color to hue {h}, saturation {s}, value {v}");
174+
175+
}
176+
_ => (),
177+
}
178+
179+
println!("13) De-structure nested structs and tuples");
180+
let ((feet, inches), Point { x, y, z }) = ((3,10), Point{x:3, y:-10, z:5});
181+
println!("{feet}-feet, {inches}-inches, Point x={x}, y={y}, z={z}");
182+
183+
184+
println!("14) Ignore parts of a value with a nested _");
185+
let mut setting_value = Some(5);
186+
let new_setting_value = Some(10);
187+
match (setting_value, new_setting_value) {
188+
(Some(_), Some(_)) => {
189+
println!("Can't overwrite an existing customized value");
190+
}
191+
_ => {
192+
setting_value = new_setting_value;
193+
}
194+
195+
}
196+
println!("setting is {:?}", setting_value);
197+
198+
let numbers = (2, 4, 8, 16, 32);
199+
match numbers {
200+
(first, _, third, _, fifth) => {
201+
println!("Some numbers: 1st={first}, 3rd={third}, 5th={fifth}");
202+
}
203+
}
204+
println!("15) Ignore remaining parts of a value ..");
205+
let origin = Point{x:0, y:0, z:0};
206+
match origin{
207+
Point{x, ..} => println!("x is {x}"),
208+
}
209+
210+
println!("16) Match Guard ..");
211+
let num = Some(4);
212+
match num {
213+
Some(x) if x%2==0 => println!("number {x} is even."),
214+
Some(x) => println!("number {x} is odd"),
215+
None => (),
216+
}
217+
218+
let x = Some(5);
219+
let y = 10;
220+
match x {
221+
Some(50) => println!("Got 50"),
222+
Some(n) if n==y => println!("Matched, n={n}"),
223+
_ => println!("Default case, x={:?}", x),
224+
}
225+
println!("At the end: x={:?}, y={y}", x);
226+
227+
println!("17) @ Bindings ..");
228+
enum Message3 {
229+
Hello {id: i32},
230+
}
231+
let msg = Message3::Hello {id: 5};
232+
match msg {
233+
Message3::Hello{id: id_variable @ 3..=7, } =>
234+
println!("Found an id in range [3-7]: {id_variable}"),
235+
Message3::Hello{id: 10..=12} => println!("Foudn an id in another range"),
236+
Message3::Hello{id} => println!("Found some other id: {id}"),
237+
}
238+
31239
}

0 commit comments

Comments
 (0)