【发布时间】:2019-06-11 12:48:08
【问题描述】:
我对此问题有一个后续问题:Expose a HashMap in a generic way that disregards the HashMap value
假设我想使用HashMapContainer(与上一个问题的第一个答案中定义的相同)作为另一个结构(我们称之为MyDB)和MyDB构造函数中的成员,我想决定是否将此成员构造为HashMapContainerImpl1 或HashMapContainerImpl2。我不想将MyDB 定义为模板(例如MyDB<T>),因为MyDB 用户不关心HashMap 的值(MyDB 构造函数将决定这一点)。实现它的正确方法是什么?
这是我想要实现的示例代码(它不会编译):
pub trait HashMapContainer {
type Value;
fn get_hash_map(&self) -> &HashMap<String, Self::Value>;
fn get_hash_map_mut(&mut self) -> &mut HashMap<String, Self::Value>;
}
struct MyDB {
hash_container: HashMapContainer
}
impl MyDB {
pub fn new(hash_value_type: &str) -> MyDB {
// have a logic to set hash_container to either
// HashMapContainerImpl1 or HashMapContainerImpl2
// according to hash_value_type
}
pub fn count_keys(&self) -> usize {
self.hash_container.get_hash_map().len()
}
}
fn main() {
let db = MyDB::new();
println!("key count: {}", db.count_keys());
}
【问题讨论】:
-
这个链接确实是相关的,但不能解决定义结构成员的问题,该成员是具有关联类型的特征