Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trait Foo {
- fn method(&self) -> String;
- }
- impl Foo for u8 {
- fn method(&self) -> String {
- // implicit return String
- format!("u8: {}", *self)
- }
- }
- impl Foo for String {
- fn method(&self) -> String {
- format!("String: {}", *self)
- }
- }
- // A trait bound on a method
- // The function do_something is a generic function
- // with template T that is bound by the trait Foo, i.e the T type must
- // implement Foo trait in order to be used inside the function do_something
- /// The generic method leads to static dispatch in some cases
- /// that is the call `do_something(34)` will make Rust create a
- /// version of do_something(p: i32) -> String {}
- /// this is great for inlining but is going to cause code bloat
- fn do_something<T: Foo>(p: T) -> String {
- p.method()
- }
- /// Note: Rustlang doesn't support `overloading`
- /// The below function is going to ‘erase’ the compiler’s knowledge
- /// about the specific type of the pointer,
- /// and hence trait objects are sometimes referred to as ‘type erasure’.
- /// we can use the same trait to perform dynamic dispatch with trait objects
- /// * by casting
- /// * by coercing
- fn do_something_traitobj(p: &Foo) -> String {
- p.method()
- }
- /**
- A trait object can be obtained from a pointer to a concrete type that
- implements the trait by casting it (e.g. &x as &Foo) or coercing it
- (e.g. using &x as an argument to a function that takes &Foo).
- */
- fn main() {
- println!("Hey there!");
- println!("{}", do_something(34));
- println!("{}", do_something(String::from("Hey there")));
- // since u8 and String implement the trait Foo
- // trait objects can be obtained from the instances of these types,
- // since u8 and String are the concrete types.
- // casting
- let prev = 5u8;
- println!("casting: {prev} to {value}",
- prev = &prev,
- value = do_something_traitobj(&prev as &Foo));
- // coercing
- let my_string: String = String::from("My String");
- // in this case, by passing the borrowed reference of my_string to
- // do_something_traitobj(), my_string was coerced to the &Foo type
- // hence causing a dynamic dispatch. The Rustlang compiler is not able to
- // figure out the
- println!("coercing: {prev} to {value}",
- prev = &my_string,
- value = do_something_traitobj(&my_string));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement