Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created May 13, 2018 17:08
Show Gist options
  • Save rust-play/43ac5166e9173a556f0b0235b2ea6177 to your computer and use it in GitHub Desktop.
Save rust-play/43ac5166e9173a556f0b0235b2ea6177 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::collections::HashMap;
use std::fmt::Debug;
pub trait StaticBuilder {
fn build(&self) -> Box<HasName>;
}
struct UserBuilder;
impl StaticBuilder for UserBuilder {
fn build(&self) -> Box<HasName> {
Box::new(User::new())
}
}
pub fn type_registry() -> HashMap<u16, Box<StaticBuilder>> {
let mut m: HashMap<u16, Box<StaticBuilder>> = HashMap::new();
m.insert(1 as u16, Box::new(UserBuilder));
// m.insert(2 as u16, Box::new(ProfileBuilder));
m
}
fn main() {
let type_registry = type_registry();
let builder = type_registry.get(&(1 as u16)).unwrap();
println!("{:?}", builder.build());
}
pub trait HasName: Debug {
fn get_name(&self) -> String;
}
#[derive(Debug)]
struct User {
name: String
}
impl User {
fn new() -> Self {
User {
name: "jonah".to_string(),
}
}
}
impl HasName for User {
fn get_name(&self) -> String {
self.name.clone()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment