Created
November 8, 2017 09:18
-
-
Save matklad/2ae1814fd7214f25cf13310c1c0d1350 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
trait Counter: 'static { | |
fn create(data: &str) -> Self where Self: Sized; | |
} | |
struct CounterA(i32); | |
impl Counter for CounterA { | |
fn create(data: &str) -> Self where Self: Sized { | |
CounterA(data.parse::<i32>().unwrap()) | |
} | |
} | |
struct CounterB(f64); | |
impl Counter for CounterB { | |
fn create(data: &str) -> Self where Self: Sized { | |
CounterB(data.parse::<f64>().unwrap()) | |
} | |
} | |
fn create_counter(name: &str, data: &str) -> Box<Counter> { | |
fn create<C: Counter>(data: &str) -> Box<Counter> { Box::new(C::create(data)) } | |
let registry: &[(&str, fn(&str) -> Box<Counter>)] = &[ | |
("A", create::<CounterA>), | |
("B", create::<CounterB>), | |
]; | |
for &(n, ctor) in registry { | |
if n == name { | |
return ctor(data); | |
} | |
} | |
panic!("Unknown counter {}", name) | |
} | |
fn main() { | |
println!("Hello, world!"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment