代码之家  ›  专栏  ›  技术社区  ›  Max

未自动转换为引用的框

  •  3
  • Max  · 技术社区  · 6 年前

    我正在存储一个 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>

    1 回复  |  直到 6 年前
        1
  •  3
  •   antoyo    6 年前

    impl B for C {
        fn get(&self, key: &'static str) -> Option<&A> {
            return self.map.get(key).map(|value| &**value)
        }
    }