Skip to content

Instantly share code, notes, and snippets.

@Rahix
Last active December 29, 2018 13:05
Show Gist options
  • 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 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