Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.62 KB | None | 0 0
  1. use std::collections::HashMap;
  2.  
  3. struct A {}
  4. struct B {}
  5.  
  6. trait MyTrait {
  7. fn print_hello(&self);
  8. }
  9.  
  10. impl MyTrait for A {
  11. fn print_hello(&self) {
  12. println!("I am A");
  13. }
  14. }
  15. impl MyTrait for B {
  16. fn print_hello(&self) {
  17. println!("I am B");
  18. }
  19. }
  20.  
  21. fn main() {
  22. let a = Box::new(A {});
  23. let b = Box::new(B {});
  24. let mut dict: HashMap<&str, Box<dyn MyTrait>> = HashMap::new();
  25. dict.insert("a", a);
  26. dict.insert("b", b);
  27.  
  28. match dict.get("a") {
  29. Some(my_trait) => {
  30. my_trait.print_hello();
  31. }
  32. None => {
  33. println!("Struct not found");
  34. }
  35. }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement