Guest User

Untitled

a guest
Jun 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.93 KB | None | 0 0
  1. trait Foo {
  2. fn something(&self) {
  3. self.method();
  4. }
  5.  
  6. fn method(&self);
  7. }
  8.  
  9. impl Foo for String {
  10. fn method(&self) {
  11. println!("In String");
  12. }
  13. }
  14.  
  15. impl Foo for i32 {
  16. fn method(&self) {
  17. println!("In i32");
  18. }
  19. }
  20.  
  21. fn main() {
  22. let x = String::new();
  23. use_impl_trait(&x);
  24. use_trait_object(&x);
  25. use_trait_object_by_box(Box::new(&x));
  26. use_trait_object_by_dyn(&x);
  27.  
  28. let x: i32 = 0;
  29. use_impl_trait(&x);
  30. use_trait_object(&x);
  31. use_trait_object_by_box(Box::new(&x));
  32. use_trait_object_by_dyn(&x);
  33. }
  34.  
  35. fn use_impl_trait(f: &impl Foo) {
  36. println!("Use Impl Trait");
  37. f.something();
  38. }
  39.  
  40. fn use_trait_object(f: &Foo) {
  41. println!("Use Trait Object");
  42. f.something();
  43. }
  44.  
  45. fn use_trait_object_by_box(b: Box<&Foo>) {
  46. println!("Use Trait Object By Box");
  47. b.something();
  48. }
  49.  
  50. fn use_trait_object_by_dyn(f: &dyn Foo) {
  51. println!("Use Trait Object By Dyn");
  52. f.something();
  53. }
Add Comment
Please, Sign In to add comment