forked from eliovir/rust-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtutorial-04_2-pattern-matching.rs
71 lines (63 loc) · 1.88 KB
/
tutorial-04_2-pattern-matching.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//! 4.2 Pattern matching
//! http://doc.rust-lang.org/tutorial.html#pattern-matching
//!
//! Tested with rust-1.41.1-nightly
//!
//! @license MIT license <http://www.opensource.org/licenses/mit-license.php>
extern crate rand;
use std::f64;
use rand::Rng;
struct Point { x: f64, y: f64 }
fn angle(vector: (f64, f64)) -> f64 {
let pi = f64::consts::PI;
match vector {
(x, y) if x == 0.0 && y < 0.0 => 1.5 * pi,
(x, _) if x == 0.0 => 0.5 * pi,
(x, y) => (y / x).atan()
}
}
fn main() {
let my_number: u32 = rand::thread_rng().gen_range(0, 10);
println!("my_number = {}", my_number);
/*
* Rust's match construct is a generalized, cleaned-up version of C's
* switch construct. You provide it with a value and a number of arms,
* each labelled with a pattern, and the code compares the value
* against each pattern in order until one matches. The matching
* pattern executes its corresponding arm.
*/
match my_number {
0 => println!("zero"),
1 | 2 => println!("one or two"),
3..=10 => println!("three to ten"),
_ => println!("something else")
}
/*
* match constructs must be exhaustive: they must have an arm covering
* every possible case. For example, the typechecker would reject the
* previous example if the arm with the wildcard pattern was omitted.
*/
match my_number {
0 => { println!("zero") }
_ => { println!("something else") }
}
let age: u32 = rand::thread_rng().gen_range(0, 100);
println!("age = {}", age);
match age {
a @ 0..=20 => println!("{} years old", a),
_ => println!("older than 21")
}
let vector = (1f64,1f64);
println!("angle({:?}) == {:?}", vector, angle(vector));
/*
* To destructure a struct, use `..`.
* http://doc.rust-lang.org/tutorial.html#structs
*/
let mypoint = Point { x: 0.0, y: 0.0 };
match mypoint {
Point { x, .. } => println!("{}", x),
}
match mypoint {
Point { y, .. } => println!("y={}", y),
}
}