Skip to content

Instantly share code, notes, and snippets.

@matklad
Created November 8, 2017 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matklad/2ae1814fd7214f25cf13310c1c0d1350 to your computer and use it in GitHub Desktop.
Save matklad/2ae1814fd7214f25cf13310c1c0d1350 to your computer and use it in GitHub Desktop.
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