Having and using trait objects

Hi,
Why do I ever need to have/create Trait Object?

1 Like

Trait objects basically allow for the programming style that is common in "object-oriented" programming languages like C# or Java: you have a bunch objects which only have it in common that they implement a certain interface (Trait, in Rust terms), and you want to manipulate them in the same way at runtime by storing them together in the same collections, iterating through the collection by calling the same method on all trait objects, etc.

It has some runtime costs (basically pointer indirection everywhere), but it makes some things like GUI programming really convenient. After all, does your Window really need to know that it is storing a TabbedLayout whose first tab contains a HorizontalLayout of VerticalLayout of Labels and Buttons, with an extra unlabeled Button at the bottom, and whose second tab contains a ScrollableWrapper of RichTextEdit? An enum- or generic-based solution to this problem would quickly become really unwieldy!

1 Like

It is rust's way of getting dynamic dispatch or runtime polymorphism.

In classical object-oriented programming, you can conceptually have a vector of some base class, and objects of any subclass can be stored in that vector. If you iterate over the vector of items, calling a specific base-class method, the actual method invoked depends on the stored object's actual (subclassed) type.

You can similarly have a vector of trait objects in rust. If you iterate over them and call trait methods on them, for each object, the trait method implemented for that object's actual type is called.

For more details and a practical example, I refer you to the new rust book.
https://doc.rust-lang.org/book/second-edition/ch17-02-trait-objects.html

2 Likes

Thank you a lot!