I have a follow up question to this question: Expose a HashMap in a generic way that disregards the HashMap value
Suppose I want to use HashMapContainer
(the same one that was defined in the previous question's first answer) as a member in another struct (let's call it MyDB
) and in MyDB
constructor I want to decide whether to construct this member as HashMapContainerImpl1
or HashMapContainerImpl2
. I don't want to define MyDB
as a template (e.g MyDB<T>
) because MyDB
users don't care about the value of the HashMap
(MyDB
constructor will decide about that). What is the right way to implement that?
Here is a sample code of what I want to achieve (it doesn't compile):
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());
}