Rc/Box upcast

Is it possible to introduce a trait-based upcast method to Rust's std::{rc::Rc, sync::Arc, boxed::Box}? There's already downcast().

By "upcast" I mean a covariant conversion. For example, I want to cast from subtype trait Control to super type trait DisplayObject.

You might want to specify what you mean by "upcast", otherwise this is a meaningless/ambiguous proposal.

1 Like

I mean subtype-to-super type (covariant, BTrait-to-ATrait) conversion.

Subtype” is a technical term in the context of Rust, and probably not what you mean. If you’re referring to subtraits / supertraits, and also you’re talking about trait objects, then note there’s already an in-development feature for allowing such conversions:

trait_upcasting - The Rust Unstable Book

For the time being, most that this particular feature has to offer can be achieved in a workaround way by adding appropriate conversion methods to your traits manually; and can be made ergonomic (i.e. non boilerplatey to implement), too, with helper traits and blanket implementations.

In any case, a code example of what kind of feature / operation you're asking for would be enlightening. And/or just generally a more verbost description of what you’re after. It’s hard to work with statements so vague that they could mean about 10 different things at once.

I’m imagining this thread could be related to some parts of the discussion over in Is it possible to add new methods to a trait from an external crate? - help - The Rust Programming Language Forum. (I haven’t really read that thread yet though.) Note that downcasting between trait objects in a trait “hierarchy” (in terms of subtrait/supertrait relations), i.e. going from a supertrait trait object to a subtrait trait object (i.e. the direction that can fail) would be way more nontrivial than upcasting; just in case that's what you're after here.


Sometime I was trying to use Rust to implement my own scripting language's semantic data model and gave up because I wasn't sure using Rc/Weak would work. Now, I want to use Rust for another thing, I'm interested in implementing something like Flash Player's display list (DisplayObjects), but I didn't write code for that yet, even because I may end up writting wrong code.

Nice, it works! Now I just need to solve the last problem in the topic, but that upcasting is solved.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.