Guest User

Untitled

a guest
Sep 20th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.81 KB | None | 0 0
  1. // Example trait
  2. trait MyTrait {
  3. fn foo(&self);
  4. }
  5.  
  6. // Implementations of the trait for (i32, i32) and "str"
  7. type MyType = (i32, i32);
  8.  
  9. impl MyTrait for MyType {
  10. fn foo(&self) {
  11. println!("{} {}", self.0, self.1);
  12. }
  13. }
  14.  
  15. impl MyTrait for &'static str {
  16. fn foo(&self) {
  17. println!("{}", self);
  18. }
  19. }
  20.  
  21. // Actual example how to avoid repeating Box::new or add_item()
  22. fn show_all(mt: Vec<&dyn MyTrait>) {
  23. // List original
  24. for ref item in &mt {
  25. item.foo();
  26. }
  27.  
  28. // Box all
  29. let mut boxed = Vec::new();
  30. for ref item in &mt {
  31. boxed.push(Box::new(*item));
  32. }
  33.  
  34. // List boxed
  35. for ref item in &boxed {
  36. item.foo();
  37. }
  38. }
  39.  
  40. // How to invoke.
  41. fn main() {
  42. show_all(vec![
  43. &"test",
  44. &(1, 2),
  45. &"blah",
  46. &(5, 7),
  47. ]);
  48. }
Add Comment
Please, Sign In to add comment