Arc::downcast a type Arc<Mutex<Any + Send + Sync + 'static>>



I am facing a problem using Any into Arc<Mutex<>>.

I would use an HashMap as a container and store different types and share it between threads. I could not find a way to get Any and downcast to the original type.

You may find the code in playground using the link.

playground link

The part of code I can’t make working:

`type Item = Arc<Mutex<Any + Send + Sync + 'static>>;

let mut container: HashMap<String, Item> = HashMap::new();

container.insert("s1_1".to_string(), Arc::new(Mutex::new(s1_1)));
container.insert("s1_2".to_string(), Arc::new(Mutex::new(s1_2)));
container.insert("s2_1".to_string(), Arc::new(Mutex::new(s2_1)));
container.insert("s2_2".to_string(), Arc::new(Mutex::new(s2_2)));

// How to get an instance from HashMap and downcast it ?
// I am trying to do it step by step

// 1) Get instance from HashMap
let mut a = container.get("s1_1").unwrap();

// 2) Create a clone of Arc
let mut b = Arc::clone(a);

// 3) downcast to the struct From Any
let mut c = Arc::downcast::<Mutex<DummyS1>>(b).unwrap();

// 4) Print debug instance
println!("> :{:?}", c.lock().unwrap());`

Thanks for your advice’s


Hi, I got it working like that.
You were trying to downcast the Arc but it doesn’t contain the Any, it contains a Mutex.
I just locked the mutex to access the Any and then downcasted it.


Thanks ! :+1: