Matthias Benkard | 848739c | 2019-02-28 13:59:58 +0100 | [diff] [blame^] | 1 | // Generic Programming: Dynamic Polymorphism |
Matthias Benkard | f3a3b30 | 2019-02-28 12:13:56 +0100 | [diff] [blame] | 2 | |
| 3 | #![allow(dead_code)] |
| 4 | #![allow(unused_imports)] |
| 5 | |
| 6 | use rust_tutorial::*; |
| 7 | |
Matthias Benkard | 848739c | 2019-02-28 13:59:58 +0100 | [diff] [blame^] | 8 | fn stringify_all(xs: Vec<&dyn ToString>) -> String { |
| 9 | let strings: Vec<String> = |
| 10 | xs.iter().map(|x| x.to_string()).collect(); |
| 11 | |
| 12 | strings.join(", ") |
| 13 | } |
| 14 | |
Matthias Benkard | f3a3b30 | 2019-02-28 12:13:56 +0100 | [diff] [blame] | 15 | fn main() { |
Matthias Benkard | 848739c | 2019-02-28 13:59:58 +0100 | [diff] [blame^] | 16 | let mut stringlike_things: Vec<&dyn ToString> = Vec::new(); |
| 17 | |
| 18 | let x1 = "abc"; |
| 19 | let x2 = 100; |
| 20 | let x3 = Person { age: 30, name: "Mary".to_string() }; |
| 21 | |
| 22 | stringlike_things.push(&x1); |
| 23 | stringlike_things.push(&x2); |
| 24 | stringlike_things.push(&x3); |
| 25 | |
| 26 | println!("{}", stringify_all(stringlike_things)); |
Matthias Benkard | f3a3b30 | 2019-02-28 12:13:56 +0100 | [diff] [blame] | 27 | } |