Skip to content

Comment on Rust Any part 3: we have upcastsparent

Comments

This example shows how it works for one trait, Debug, but what if you have a type that (might) implement multiple traits A, B, and/or C? It isn't clear to me if that is possible, unless the type implements all of those traits.

Yeah, you can do the same trick if you care about types that implement all of A, B and C.

What I'd like to do is have some base trait object and query it to see if it supports other interfaces, but also not have to have stub "I don't actually implement this" trait impls for the unsupported ones.

Currently this is not possible, though it might be possible in the future once Rust gets specialization. With that you would basically be able to write the "I don't actually implement this" stub automatically. The catch however would be that this can only work for `'static` types, since such specialization for non-`'static` types is unsound.

I believe I understand that in rust this has not historically been possible because rust doesn't have inheritance, so, there can be only one vtable for a type, rather than an chain like you might have in c++.

The issue is kinda the opposite. In Rust types can implement any number of traits (even infinite!), so they would require an potentially an infinite amount of vtables if implemented like in C++, which is just not possible. So instead this is splitted from types and moved to trait objects, which allow to carry a vtable for one specific trait.

AboutSource Built by g1lg1l

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