Advertisement
Guest User

Untitled

a guest
Apr 30th, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. trait Foo {
  2. fn method(&self) -> String;
  3. }
  4.  
  5. impl Foo for u8 {
  6. fn method(&self) -> String {
  7. // implicit return String
  8. format!("u8: {}", *self)
  9. }
  10. }
  11.  
  12. impl Foo for String {
  13. fn method(&self) -> String {
  14.  
  15. format!("String: {}", *self)
  16. }
  17. }
  18.  
  19.  
  20. // A trait bound on a method
  21. // The function do_something is a generic function
  22. // with template T that is bound by the trait Foo, i.e the T type must
  23. // implement Foo trait in order to be used inside the function do_something
  24. /// The generic method leads to static dispatch in some cases
  25. /// that is the call `do_something(34)` will make Rust create a
  26. /// version of do_something(p: i32) -> String {}
  27. /// this is great for inlining but is going to cause code bloat
  28. fn do_something<T: Foo>(p: T) -> String {
  29.  
  30. p.method()
  31. }
  32.  
  33. /// Note: Rustlang doesn't support `overloading`
  34. /// The below function is going to ‘erase’ the compiler’s knowledge
  35. /// about the specific type of the pointer,
  36. /// and hence trait objects are sometimes referred to as ‘type erasure’.
  37. /// we can use the same trait to perform dynamic dispatch with trait objects
  38. /// * by casting
  39. /// * by coercing
  40. fn do_something_traitobj(p: &Foo) -> String {
  41.  
  42. p.method()
  43. }
  44.  
  45. /**
  46. A trait object can be obtained from a pointer to a concrete type that
  47. implements the trait by casting it (e.g. &x as &Foo) or coercing it
  48. (e.g. using &x as an argument to a function that takes &Foo).
  49. */
  50. fn main() {
  51.  
  52. println!("Hey there!");
  53. println!("{}", do_something(34));
  54. println!("{}", do_something(String::from("Hey there")));
  55.  
  56. // since u8 and String implement the trait Foo
  57. // trait objects can be obtained from the instances of these types,
  58. // since u8 and String are the concrete types.
  59.  
  60. // casting
  61. let prev = 5u8;
  62. println!("casting: {prev} to {value}",
  63. prev = &prev,
  64. value = do_something_traitobj(&prev as &Foo));
  65.  
  66. // coercing
  67. let my_string: String = String::from("My String");
  68. // in this case, by passing the borrowed reference of my_string to
  69. // do_something_traitobj(), my_string was coerced to the &Foo type
  70. // hence causing a dynamic dispatch. The Rustlang compiler is not able to
  71. // figure out the
  72. println!("coercing: {prev} to {value}",
  73. prev = &my_string,
  74. value = do_something_traitobj(&my_string));
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement