Reputation: 15975
I am storing a Box
in a HashMap
. I would like to retrieve those values and convert them into references to the boxed type. My code looks like this:
use std::collections::HashMap;
trait A {}
trait B {
fn get(&self, key: &'static str) -> Option<&A>;
}
struct C {
map: HashMap<&'static str, Box<A>>,
}
impl B for C {
fn get(&self, key: &'static str) -> Option<&A> {
return self.map.get(key)
}
}
The error I get is:
expected trait A, found struct `std::boxed::Box`
What is the proper way to convert Option<&Box<&A>>
to Option<&A>
?
Upvotes: 4
Views: 791
Reputation: 11933
You can dereference the box and create a reference to it:
impl B for C {
fn get(&self, key: &'static str) -> Option<&A> {
return self.map.get(key).map(|value| &**value)
}
}
Upvotes: 3