Lack one line to complete today's mind


#1

I use iron to write a web service application… today i design app struct. I want to make

App struct as global context for every request, so i use persistent library. The issue

is in App field service, this is a hashmap type var, i store a service list, the service all

is impl ServiceContract, actually, the hashmap store the Trait Object.

But now, when i write get_service method, i meet a issue, because i use HashMap::get()

method to get special service, i get a reference &Box, i dont know how

to convert it to Arc, i try some way, but i meet something complier error like lifetime,

like cant move borrrow content, i am misunderstand these, and dont know how t continue to

finish it, Are there some suggestion to me.

Thanks very much.


impl Key for App {
    type Value = App;
}

pub struct App {
    services: Arc<HashMap<String, Box<ServiceContract>>>,
    pub shared_context: Arc<SharedContext>,
}

impl App {
    pub fn new(env: &Env) -> App {
        App {
            services: Arc::new(HashMap::new()),
            shared_context: Arc::new(SharedContext::new(&env)),
        }
    }

    pub fn start(mut self) -> Chain {
        let router = App::register_resources();
        let mut chain = Chain::new(router);
        chain.link(Read::<App>::both(self));

        chain
    }

    // pub fn register_services(&mut self) {
    //     let user_service = UserService::new();
    //     self.services.insert(user_service.get_service_name(), Arc::new(user_service));
    // }

    pub fn register_resources() -> Router {
        let router = Router::new();
        let mut resource_config = ResourceConfig::new();
        resource_config.register_resources(UserResource::resources());

        router
    }

    pub fn get_service(&self, name: &str) -> Arc<Box<ServiceContract>> {
        if self.services.contains_key(name) {
           // this line, i cant complete, lifetime or reference make me misunderstand
        } else {
            panic!("Could not find `{:?}` service", name);
        }
    }
}


#2

If you want to return an Arc value, you need to store an Arc value inside the hashmap. Otherwise, you may want to try returning an &ServiceContract type from get_service instead.