dimanche 20 octobre 2019

Rust fabric pattern

I want to implement fome kind of fabric pattern in rust. Below is a simple representations of what I have so far. I have a trait A which is a fabric "builder" that creates instances (just for example I used i32, but actually it's gonna be some struct), struct B is an implementation for building specific objects and struct C has a key-value map of all builders.

Problems begin when you get to C::foo method, compiler says: std::boxed::Box, which does not implement the Copy trait. Implementing Copy for each "builder" box is kind of messy.

So how would you implement this in "the rust way"?

use std::collections::HashMap;

trait A {
    fn boo(&self) -> i32;
}

struct B {}
impl A for B {
    fn boo(&self) -> i32 {
        15
    }
}

struct C {
    map: HashMap<String, Box<A>>,
}

impl C {
    pub fn new() -> C {
        C {
            map: HashMap::new()
        }
    }

    pub fn foo(&self, key: String) {
        match self.map.get(&key) {
            Some(&val) => println!("{}", val.boo()),
            _ => println!("None")
        }
    }
}
fn main() {
    let c = C::new();
    c.foo(String::from("bar"));
}

Aucun commentaire:

Enregistrer un commentaire