Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Behavior Inheritance in Rust (2021) (abadcafe.wordpress.com)
26 points by fanf2 on July 2, 2024 | hide | past | favorite | 5 comments


This is a nice example to do inheritance the Rust-way using composition instead of OO, but still I'm missing some essential parts for which I have not found the proper Rust idioms yet.

For example, when building a widget hierarchy, I would like to be able to pass widgets of different types to a function or store them in a `Vec<>`, but this is not possible since these are different concrete types.

Trait objects can help here, but then Rust lacks the machinery to upcast and downcast between types as there is no RTTI attached to these trait objects; you can not cast/convert a `Button` to a `BaseWidget`, or a `BaseWidget` that was originally a `Button` back to a `Button`.

What would be the rusty way to handle this?


I think what you're looking for is std::any; https://doc.rust-lang.org/std/any/index.html

The example there includes a function that takes Any + Debug, tries to downcast to a String, and if that succeeds it logs the string length


Right, it seems `Any` and `downcast_ref::<>` were the missing parts for the downcasting. Upcasting is new in nightly with `#![feature(trait_upcasting)]`


Did not know this existed!


For what it’s worth, this exact pattern is essentially entirely what’s implied by “composition over inheritance”.

Nice to have a concise example written down though.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: