我在Box
存储HashMap
。我想检索这些值并将它们转换为对盒装类型的引用。我的代码看起来像这样:
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)
}
}
我得到的错误是:
expected trait A, found struct `std::boxed::Box`
将Option<&Box<&A>>
转换为Option<&A>
的正确方法是什么?
您可以取消引用该框并创建对它的引用:
impl B for C {
fn get(&self, key: &'static str) -> Option<&A> {
return self.map.get(key).map(|value| &**value)
}
}