Skip to content

Instantly share code, notes, and snippets.

@Rahix
Last active December 29, 2018 13:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rahix/75e9bfc17aa30834d752f80672930b0e to your computer and use it in GitHub Desktop.
Save Rahix/75e9bfc17aa30834d752f80672930b0e to your computer and use it in GitHub Desktop.
Static and Dynamic Dispatch at the same time
trait Foo {
fn bar(&self);
}
impl Foo for &dyn Foo {
fn bar(&self) {
(*self).bar();
}
}
struct Bar;
impl Foo for Bar {
fn bar(&self) {
println!("Hello");
}
}
fn foo<T: Foo>(f: &T) {
f.bar();
}
fn baz(f: &dyn Foo) {
foo(&f)
}
fn main() {
let b = Bar;
foo(&b);
baz(&b);
}
@Rahix
Copy link
Author

Rahix commented Dec 28, 2018

By implementing a Trait for &dyn Trait (or/and &mut dyn Trait, Box<dyn Trait>), you can allow calling statically dispatched code with a trait-object. This allows reusing the statically dispatched implementation with a dynamically dispatched trait-object. Use with care

@Rahix
Copy link
Author

Rahix commented Dec 29, 2018

Actually this is better:

trait Foo {
    fn bar(&self);
}

impl Foo for &dyn Foo {
    fn bar(&self) {
        (*self).bar();
    }
}

struct Bar;

impl Foo for Bar {
    fn bar(&self) {
        println!("Hello");
    }
}

fn foo<T: Foo>(f: &T) {
    f.bar();
}

fn baz(f: &dyn Foo) {
    foo(&f)
}

fn main() {
    let b = Bar;
    
    foo(&b);
    baz(&b);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment