Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- trait Foo {
- fn something(&self) {
- self.method();
- }
- fn method(&self);
- }
- impl Foo for String {
- fn method(&self) {
- println!("In String");
- }
- }
- impl Foo for i32 {
- fn method(&self) {
- println!("In i32");
- }
- }
- fn main() {
- let x = String::new();
- use_impl_trait(&x);
- use_trait_object(&x);
- use_trait_object_by_box(Box::new(&x));
- use_trait_object_by_dyn(&x);
- let x: i32 = 0;
- use_impl_trait(&x);
- use_trait_object(&x);
- use_trait_object_by_box(Box::new(&x));
- use_trait_object_by_dyn(&x);
- }
- fn use_impl_trait(f: &impl Foo) {
- println!("Use Impl Trait");
- f.something();
- }
- fn use_trait_object(f: &Foo) {
- println!("Use Trait Object");
- f.something();
- }
- fn use_trait_object_by_box(b: Box<&Foo>) {
- println!("Use Trait Object By Box");
- b.something();
- }
- fn use_trait_object_by_dyn(f: &dyn Foo) {
- println!("Use Trait Object By Dyn");
- f.something();
- }
Add Comment
Please, Sign In to add comment