This repository has been archived by the owner on Mar 11, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
enums.rs
53 lines (49 loc) · 1.53 KB
/
enums.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
// An attribute to hide warnings for unused code.
#![allow(dead_code)]
// Create an `enum` to classify a web event. Note how both
// names and type information together specify the variant:
// `PageLoad != PageUnload` and `KeyPress(char) != Paste(String)`.
// Each is different and independent.
enum WebEvent {
// An `enum` may either be `unit-like`,
PageLoad,
PageUnload,
// like tuple structs,
KeyPress(char),
Paste(String),
// or like structures.
Click { x: i64, y: i64 },
}
// A function which takes a `WebEvent` enum as an argument and
// returns nothing.
fn inspect(event: WebEvent) -> i64 {
match event {
WebEvent::PageLoad => 1,
WebEvent::PageUnload => 2,
// Destructure `c` from inside the `enum`.
WebEvent::KeyPress(c) => 3,
WebEvent::Paste(s) => 4,
// Destructure `Click` into `x` and `y`.
WebEvent::Click { x, y } => {
x + y
},
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_works() {
let pressed = WebEvent::KeyPress('x');
// `to_owned()` creates an owned `String` from a string slice.
let pasted = WebEvent::Paste("my text".to_owned());
let click = WebEvent::Click { x: 20, y: 80 };
let load = WebEvent::PageLoad;
let unload = WebEvent::PageUnload;
assert_eq!(inspect(pressed), 3);
assert_eq!(inspect(pasted), 4);
assert_eq!(inspect(click), 100);
assert_eq!(inspect(load), 1);
assert_eq!(inspect(unload), 2);
}
}