You can add Clone in the definition of the type that is enclosed in Box.
Something like this
use std::collections::HashMap;
pub trait Service {}
#[derive(Clone)]
pub struct Services<T>
where
T: Service, //<--------
T: Clone //<----------- {
providers: std::collections::HashMap<String, Box<T>>
}
#[derive(Clone)]
pub struct A{}
impl Service for A {}
fn main()
{
let mut v: HashMap<String, Box<A>> = HashMap::new();
v.insert("test".to_string(), Box::new(A{}));
let o = Services{providers: v };
for (key, _) in o.providers.iter() {
println!("key: {} ", key);
}
}
The Sean version could be like this
use std::collections::HashMap;
use std::sync::Arc;
pub trait Service {}
#[derive(Clone)]
pub struct Services {
providers: Arc<std::collections::HashMap<String, Box<dyn Service>>>
}
#[derive(Clone)]
pub struct A{}
impl Service for A {}
#[derive(Clone)]
pub struct B{}
impl Service for B {}
fn main()
{
let mut objects: HashMap<String, Box<dyn Service>> = HashMap::new();
objects.insert("test".to_string(), Box::new(A{}));
objects.insert("test2".to_string(), Box::new(B{}));
let v = Arc::new(objects);
let o = Services{providers: v};
for (key, _) in o.providers.iter() {
println!("key: {} ", key);
}
}