Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::any::Any;
- use std::collections::HashMap;
- use std::fmt;
- use std::sync::{Arc, Mutex};
- // Create some Dummy struct to illustrate by creating
- // two different struct
- struct DummyS1 {
- id: String,
- value: String,
- }
- impl DummyS1 {
- fn new(value: String) -> DummyS1 {
- DummyS1 {
- id: "DummyS1".to_string(),
- value,
- }
- }
- fn get_value(&self) -> String {
- self.value.clone()
- }
- fn set_value(&mut self, value: String) {
- self.value = value;
- }
- }
- impl fmt::Debug for DummyS1 {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "DummyS1 {{ id: {}, value: {} }}", self.id, self.value)
- }
- }
- struct DummyS2 {
- id: String,
- value: i32,
- }
- impl DummyS2 {
- fn new(value: i32) -> DummyS2 {
- DummyS2 {
- id: "DummyS2".to_string(),
- value,
- }
- }
- fn get_value(&self) -> i32 {
- self.value
- }
- fn set_value(&mut self, value: i32) {
- self.value = value;
- }
- }
- impl fmt::Debug for DummyS2 {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "DummyS2 {{ id: {}, value: {} }}", self.id, self.value)
- }
- }
- // End of test struct
- fn main() {
- let mut s1_1 = DummyS1::new("s1_1".to_string());
- let mut s1_2 = DummyS1::new("s1_2".to_string());
- let mut s2_1 = DummyS2::new(1);
- let mut s2_2 = DummyS2::new(2);
- type Item = Arc<Mutex<Any>>;
- 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)));
- let mut a = container.get("s1_1").unwrap();
- let mut b = Arc::clone(a);
- // This is new
- let guard = b.lock().unwrap();
- let mut c = guard.downcast_ref::<DummyS1>().unwrap();
- println!("> :{:?}", c);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement