]> git.lizzy.rs Git - rust.git/blob - src/doc/style/features/traits/objects.md
Changed issue number to 36105
[rust.git] / src / doc / style / features / traits / objects.md
1 % Using trait objects
2
3 > **[FIXME]** What are uses of trait objects other than heterogeneous collections?
4
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.
8
9 ```rust,ignore
10 struct Frame  { ... }
11 struct Button { ... }
12 struct Label  { ... }
13
14 trait Widget  { ... }
15
16 impl Widget for Frame  { ... }
17 impl Widget for Button { ... }
18 impl Widget for Label  { ... }
19
20 impl Frame {
21     fn new(contents: &[Box<Widget>]) -> Frame {
22         ...
23     }
24 }
25
26 fn make_gui() -> Box<Widget> {
27     let b: Box<Widget> = box Button::new(...);
28     let l: Box<Widget> = box Label::new(...);
29
30     box Frame::new([b, l]) as Box<Widget>
31 }
32 ```
33
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.
36
37 **Pros**:
38
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.
42
43 **Cons**:
44
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.