Box不会自动转换为引用

问题描述 投票:3回答:1

我在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>的正确方法是什么?

rust
1个回答
3
投票

您可以取消引用该框并创建对它的引用:

impl B for C {
    fn get(&self, key: &'static str) -> Option<&A> {
        return self.map.get(key).map(|value| &**value)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.