Advertisement
Guest User

Untitled

a guest
Mar 18th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. use std::any::Any;
  2. use std::collections::HashMap;
  3. use std::fmt;
  4. use std::sync::{Arc, Mutex};
  5.  
  6. // Create some Dummy struct to illustrate by creating
  7. // two different struct
  8. struct DummyS1 {
  9. id: String,
  10. value: String,
  11. }
  12.  
  13. impl DummyS1 {
  14. fn new(value: String) -> DummyS1 {
  15. DummyS1 {
  16. id: "DummyS1".to_string(),
  17. value,
  18. }
  19. }
  20.  
  21. fn get_value(&self) -> String {
  22. self.value.clone()
  23. }
  24.  
  25. fn set_value(&mut self, value: String) {
  26. self.value = value;
  27. }
  28. }
  29.  
  30. impl fmt::Debug for DummyS1 {
  31. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  32. write!(f, "DummyS1 {{ id: {}, value: {} }}", self.id, self.value)
  33. }
  34. }
  35.  
  36. struct DummyS2 {
  37. id: String,
  38. value: i32,
  39. }
  40.  
  41. impl DummyS2 {
  42. fn new(value: i32) -> DummyS2 {
  43. DummyS2 {
  44. id: "DummyS2".to_string(),
  45. value,
  46. }
  47. }
  48.  
  49. fn get_value(&self) -> i32 {
  50. self.value
  51. }
  52.  
  53. fn set_value(&mut self, value: i32) {
  54. self.value = value;
  55. }
  56. }
  57.  
  58. impl fmt::Debug for DummyS2 {
  59. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  60. write!(f, "DummyS2 {{ id: {}, value: {} }}", self.id, self.value)
  61. }
  62. }
  63.  
  64. // End of test struct
  65.  
  66. fn main() {
  67.  
  68. let mut s1_1 = DummyS1::new("s1_1".to_string());
  69. let mut s1_2 = DummyS1::new("s1_2".to_string());
  70.  
  71. let mut s2_1 = DummyS2::new(1);
  72. let mut s2_2 = DummyS2::new(2);
  73.  
  74. type Item = Arc<Mutex<Any>>;
  75.  
  76. let mut container: HashMap<String, Item> = HashMap::new();
  77.  
  78. container.insert("s1_1".to_string(), Arc::new(Mutex::new(s1_1)));
  79. container.insert("s1_2".to_string(), Arc::new(Mutex::new(s1_2)));
  80. container.insert("s2_1".to_string(), Arc::new(Mutex::new(s2_1)));
  81. container.insert("s2_2".to_string(), Arc::new(Mutex::new(s2_2)));
  82.  
  83. let mut a = container.get("s1_1").unwrap();
  84.  
  85. let mut b = Arc::clone(a);
  86.  
  87. // This is new
  88. let guard = b.lock().unwrap();
  89.  
  90. let mut c = guard.downcast_ref::<DummyS1>().unwrap();
  91.  
  92. println!("> :{:?}", c);
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement