-
Notifications
You must be signed in to change notification settings - Fork 33
/
lang-interface.rs
80 lines (69 loc) · 1.74 KB
/
lang-interface.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
72
73
74
75
76
77
78
79
/**
* Program to an 'interface', not an 'implementation'.
*
* http://joshldavis.com/2013/07/01/program-to-an-interface-fool/
*
* @author: Josh Davis
* @date: 2013-07-01
*/
/**
* Imagine you are Guy Montag from the book, Fahrenheit 451 (F451 from here on out).
* As everyone knows, books in F451 are forbidden.
* It's the job of firefighters to set them on fire whenever they come across them.
* Therefore thinking in terms of OOP, a book has a method called `burn()`.
*/
struct Book {
title: String,
author: String,
}
struct Log {
wood_type: String,
}
trait Burns {
fn burn(&self);
}
impl Burns for Log {
fn burn(&self) {
println!("The {} log is burning!", self.wood_type);
}
}
impl Burns for Book {
fn burn(&self) {
println!("The book \"{}\" by {} is burning!", self.title, self.author);
}
}
struct Incunable(Book);
impl Burns for Incunable {
fn burn(&self) {
let book: &Book = match *self {
Incunable(ref book) => book
};
println!("The incunable \"{}\" by {} is burning!", book.title, book.author);
}
}
/**
* This is where the power of programming to an interface comes in.
* Rather than expecting a Book object or a Log object, we just take in any object with any type (we call the type T) that implements the Burns interface.
*/
fn start_fire<T: Burns>(item: T) {
item.burn();
}
fn main() {
let lg = Log {
wood_type: "Oak".to_string(),
};
let book = Book {
title: "The Brothers Karamazov".to_string(),
author: "Fyodor Dostoevsky".to_string(),
};
let nuremberg_chronicle = Book {
title: "Liber Chronicarum".to_string(),
author: "Hartmann Schedel".to_string(),
};
let incunable = Incunable(nuremberg_chronicle);
// Burn the oak log!
start_fire(lg);
// Burn the book!
start_fire(book);
start_fire(incunable);
}