3 > **[FIXME]** What are uses of trait objects other than heterogeneous collections?
5 Trait objects are useful primarily when _heterogeneous_ collections of objects
6 need to be treated uniformly; it is the closest that Rust comes to
7 object-oriented programming.
16 impl Widget for Frame { ... }
17 impl Widget for Button { ... }
18 impl Widget for Label { ... }
21 fn new(contents: &[Box<Widget>]) -> Frame {
26 fn make_gui() -> Box<Widget> {
27 let b: Box<Widget> = box Button::new(...);
28 let l: Box<Widget> = box Label::new(...);
30 box Frame::new([b, l]) as Box<Widget>
34 By using trait objects, we can set up a GUI framework with a `Frame` widget that
35 contains a heterogeneous collection of children widgets.
39 * _Heterogeneity_. When you need it, you really need it.
40 * _Code size_. Unlike generics, trait objects do not generate specialized
41 (monomorphized) versions of code, which can greatly reduce code size.
45 * _No generic methods_. Trait objects cannot currently provide generic methods.
46 * _Dynamic dispatch and fat pointers_. Trait objects inherently involve
47 indirection and vtable dispatch, which can carry a performance penalty.
48 * _No Self_. Except for the method receiver argument, methods on trait objects
49 cannot use the `Self` type.