Skip to content

Comment on Rust Any part 3: we have upcastsparent

Comments

In Rust, an implementation of a trait never implements methods that weren't defined on that trait explicitly. In your example, an implementation of C inherits from B and A, but only implements B's methods. In Rust, an implementation of C cannot itself implement B's or A's methods; it is merely allowed to assume that they have been implemented elsewhere. This also means that subtraits cannot override the behavior of methods defined on supertraits.

Okay, but doesn't Bar nevertheless inherit Foo's methods in the sense of interface inheritance? Or does code that gets passed a Bar not get access to Foo's methods?

does code that gets passed a Bar not get access to Foo's methods

Prior to the current version of Rust it was impossible to access methods on `Foo` when a `&dyn Bar` was passed. With the current beta version you can upcast.

Prior to the current version of Rust it was impossible to access methods on `Foo` when a `&dyn Bar` was passed.

This has been working since Rust 1.0, I think:

    trait Foo {
        fn foo(&self);
    }
    trait Bar : Foo {}

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

    fn xxx(x: &dyn Bar) {
       x.foo();
    }

    pub fn main() {
        xxx(&());
    }
> With the current beta version you can upcast

Right. Now you can convert from `&dyn Bar` to `&dyn Foo` which wasn't possible before.

Inherent method implementations were unavailable. (Eg: impl dyn Foo) and then call this via Bar.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.