I have a reference to a hashmap (data in the code below) which I want to clone into a new, owned hashmap. Cloning the reference gives me a new reference, which is not what I need.
I also tried doing an iter + map over the data reference and cloning the key and value pairs individually followed by a collect, but that also does not work. Here is a minimal working example:
use core::cell::Cell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::rc::Rc;
struct Dummy<K, V> {
dirty: Rc<Cell<bool>>,
data: Cell<Option<HashMap<K, HashSet<V>>>>,
}
impl<K, V> Dummy<K, V> {
fn persist(&self, prefix: &str, data: &HashMap<K, HashSet<V>>) {
self.dirty.set(true);
self.data.set(Some(data.clone()));
}
}
which gives the following error:
error[E0308]: mismatched types
--> src/lib.rs:14:28
|
14 | self.data.set(Some(data.clone()));
| ^^^^^^^^^^^^ expected struct `std::collections::HashMap`, found reference
|
= note: expected type `std::collections::HashMap<K, std::collections::HashSet<V>>`
found type `&std::collections::HashMap<K, std::collections::HashSet<V>>`
The purpose of this code is to observe the contents of the hashmap on through the Dummy struct, which is used for unit testing.
I guess this problem is because given the generic types there is no way to determine how to deeply clone the key and value objects?
Is there a way to create a new hashmap given a reference to an existing hashmap?
impl<K: Clone, V: Clone>?