Hello everyone,
I have the following code:
use std::collections::HashMap;
#[derive(Debug, Clone)]
struct Child {}
#[derive(Default)]
struct A {
map: HashMap<String, Child>,
}
impl A {
pub fn default() -> A {
let mut a = A {
map: HashMap::new(),
};
a.map.insert("one".to_string(), Child{});
a
}
pub fn get_map(&self) -> HashMap<String, Child> {
self.map
}
}
fn do_something(value: Child) {
println!("Value: {}", value);
}
fn main() {
let a = A::default();
let x = a.get_map();
for (key, value) in x {
println!("{}", key);
do_something(value);
}
}
Where get_map
would return the hashmap of the struct and the loop in main would pass the value to a different function, possibly a 3rd-party crate that does something with the value.
Initially, i get the error:
21 | self.map
| ^^^^^^^^ move occurs because `self.map` has type `std::collections::HashMap<std::string::String, Child>`, which does not implement the `Copy` trait
So what i though is that i could return a reference to the map so that it's still owned by the struct.
Updated code:
impl A {
....
pub fn get_map(&self) -> &HashMap<String, Child> {
&self.map
}
}
Now i get the error:
35 | do_something(value);
| ^^^^^ expected struct `Child`, found &Child
Here, i could de-reference the value and clone it since it's clonable.
do_something((*value).clone());
However, if the Child
objects were large, it seems like this could be very inefficient.
Is the above idiomatic code? If not, how would this kind of pattern be implemented idiomatically?