Skip to content

Commit

Permalink
Merge pull request 6 from Manishearth/subtrait-dispatch
Browse files Browse the repository at this point in the history
  • Loading branch information
dtolnay committed Dec 1, 2018
2 parents bd1559a + 58eea79 commit 7c1ace3
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/27/index.html
7 changes: 7 additions & 0 deletions docs/questions.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions questions/027-subtrait-dispatch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Answer: 3311
Difficulty: 1

# Hint

All traits have an independent set of methods.


# Explanation

The trait `Base` has a default method `method`. Its impl for `OnlyBase` overrides that default method. Default methods are basically sugar for "copy this method into each trait impl that doesn't explicitly define this method". Once you override the default method there is no way to call the original default method for that given type. So both static and dynamic dispatch on `OnlyBase` produce the number `3`, from calling the `method` from `impl Base for OnlyBase`.

While subtraits _can_ define methods conflicting with the base trait, these are _independent_ methods, and do not override the original. Trait inheritance does not override methods, trait inheritance is a way of saying "all implementors of this trait _must_ implement the parent trait". Both `stat()` and `dynamic()` refer to the trait `Base`, so we look for a `method()` from `impl Base for OnlyBase`, which turns out to be the default method, so both these calls produce `1`.
36 changes: 36 additions & 0 deletions questions/027-subtrait-dispatch.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@

trait Base {
fn method(&self) {print!("1")}
}

trait Derived: Base {
fn method(&self) {print!("2")}
}

struct OnlyBase;

impl Base for OnlyBase {
fn method(&self) {print!("3")}
}


struct BothTraits;
impl Base for BothTraits {}
impl Derived for BothTraits {}

// dynamic dispatch
fn dynamic(x: &dyn Base) {
x.method()
}

// static dispatch
fn stat<T: Base>(x: &T) {
x.method();
}

fn main() {
dynamic(&OnlyBase);
stat(&OnlyBase);
dynamic(&BothTraits);
stat(&BothTraits);
}

0 comments on commit 7c1ace3

Please sign in to comment.