]> git.proxmox.com Git - rustc.git/blame - src/doc/book/src/ch17-02-trait-objects.md
New upstream version 1.55.0+dfsg1
[rustc.git] / src / doc / book / src / ch17-02-trait-objects.md
CommitLineData
9fa01778 1## Using Trait Objects That Allow for Values of Different Types
13cf67c4
XL
2
3In Chapter 8, we mentioned that one limitation of vectors is that they can
4store elements of only one type. We created a workaround in Listing 8-10 where
5we defined a `SpreadsheetCell` enum that had variants to hold integers, floats,
6and text. This meant we could store different types of data in each cell and
7still have a vector that represented a row of cells. This is a perfectly good
8solution when our interchangeable items are a fixed set of types that we know
9when our code is compiled.
10
11However, sometimes we want our library user to be able to extend the set of
12types that are valid in a particular situation. To show how we might achieve
13this, we’ll create an example graphical user interface (GUI) tool that iterates
14through a list of items, calling a `draw` method on each one to draw it to the
15screen—a common technique for GUI tools. We’ll create a library crate called
16`gui` that contains the structure of a GUI library. This crate might include
17some types for people to use, such as `Button` or `TextField`. In addition,
18`gui` users will want to create their own types that can be drawn: for
19instance, one programmer might add an `Image` and another might add a
20`SelectBox`.
21
22We won’t implement a fully fledged GUI library for this example but will show
23how the pieces would fit together. At the time of writing the library, we can’t
24know and define all the types other programmers might want to create. But we do
25know that `gui` needs to keep track of many values of different types, and it
26needs to call a `draw` method on each of these differently typed values. It
27doesn’t need to know exactly what will happen when we call the `draw` method,
28just that the value will have that method available for us to call.
29
30To do this in a language with inheritance, we might define a class named
31`Component` that has a method named `draw` on it. The other classes, such as
32`Button`, `Image`, and `SelectBox`, would inherit from `Component` and thus
33inherit the `draw` method. They could each override the `draw` method to define
34their custom behavior, but the framework could treat all of the types as if
35they were `Component` instances and call `draw` on them. But because Rust
36doesn’t have inheritance, we need another way to structure the `gui` library to
37allow users to extend it with new types.
38
39### Defining a Trait for Common Behavior
40
41To implement the behavior we want `gui` to have, we’ll define a trait named
42`Draw` that will have one method named `draw`. Then we can define a vector that
9fa01778
XL
43takes a *trait object*. A trait object points to both an instance of a type
44implementing our specified trait as well as a table used to look up trait
45methods on that type at runtime. We create a trait object by specifying some
46sort of pointer, such as a `&` reference or a `Box<T>` smart pointer, then the
47`dyn` keyword, and then specifying the relevant trait. (We’ll talk about the
13cf67c4 48reason trait objects must use a pointer in Chapter 19 in the section
9fa01778
XL
49[“Dynamically Sized Types and the `Sized` Trait.”][dynamically-sized]<!--
50ignore -->) We can use trait objects in place of a generic or concrete type.
51Wherever we use a trait object, Rust’s type system will ensure at compile time
52that any value used in that context will implement the trait object’s trait.
53Consequently, we don’t need to know all the possible types at compile time.
13cf67c4
XL
54
55We’ve mentioned that in Rust, we refrain from calling structs and enums
56“objects” to distinguish them from other languages’ objects. In a struct or
57enum, the data in the struct fields and the behavior in `impl` blocks are
58separated, whereas in other languages, the data and behavior combined into one
59concept is often labeled an object. However, trait objects *are* more like
60objects in other languages in the sense that they combine data and behavior.
61But trait objects differ from traditional objects in that we can’t add data to
62a trait object. Trait objects aren’t as generally useful as objects in other
63languages: their specific purpose is to allow abstraction across common
64behavior.
65
66Listing 17-3 shows how to define a trait named `Draw` with one method named
67`draw`:
68
69<span class="filename">Filename: src/lib.rs</span>
70
5869c6ff 71```rust,noplayground
74b04a01 72{{#rustdoc_include ../listings/ch17-oop/listing-17-03/src/lib.rs}}
13cf67c4
XL
73```
74
75<span class="caption">Listing 17-3: Definition of the `Draw` trait</span>
76
77This syntax should look familiar from our discussions on how to define traits
78in Chapter 10. Next comes some new syntax: Listing 17-4 defines a struct named
79`Screen` that holds a vector named `components`. This vector is of type
80`Box<dyn Draw>`, which is a trait object; it’s a stand-in for any type inside
81a `Box` that implements the `Draw` trait.
82
83<span class="filename">Filename: src/lib.rs</span>
84
5869c6ff 85```rust,noplayground
74b04a01 86{{#rustdoc_include ../listings/ch17-oop/listing-17-04/src/lib.rs:here}}
13cf67c4
XL
87```
88
89<span class="caption">Listing 17-4: Definition of the `Screen` struct with a
90`components` field holding a vector of trait objects that implement the `Draw`
91trait</span>
92
93On the `Screen` struct, we’ll define a method named `run` that will call the
94`draw` method on each of its `components`, as shown in Listing 17-5:
95
96<span class="filename">Filename: src/lib.rs</span>
97
5869c6ff 98```rust,noplayground
74b04a01 99{{#rustdoc_include ../listings/ch17-oop/listing-17-05/src/lib.rs:here}}
13cf67c4
XL
100```
101
102<span class="caption">Listing 17-5: A `run` method on `Screen` that calls the
103`draw` method on each component</span>
104
532ac7d7 105This works differently from defining a struct that uses a generic type
13cf67c4
XL
106parameter with trait bounds. A generic type parameter can only be substituted
107with one concrete type at a time, whereas trait objects allow for multiple
108concrete types to fill in for the trait object at runtime. For example, we
109could have defined the `Screen` struct using a generic type and a trait bound
110as in Listing 17-6:
111
112<span class="filename">Filename: src/lib.rs</span>
113
5869c6ff 114```rust,noplayground
74b04a01 115{{#rustdoc_include ../listings/ch17-oop/listing-17-06/src/lib.rs:here}}
13cf67c4
XL
116```
117
118<span class="caption">Listing 17-6: An alternate implementation of the `Screen`
119struct and its `run` method using generics and trait bounds</span>
120
121This restricts us to a `Screen` instance that has a list of components all of
122type `Button` or all of type `TextField`. If you’ll only ever have homogeneous
123collections, using generics and trait bounds is preferable because the
124definitions will be monomorphized at compile time to use the concrete types.
125
126On the other hand, with the method using trait objects, one `Screen` instance
9fa01778
XL
127can hold a `Vec<T>` that contains a `Box<Button>` as well as a
128`Box<TextField>`. Let’s look at how this works, and then we’ll talk about the
129runtime performance implications.
13cf67c4
XL
130
131### Implementing the Trait
132
133Now we’ll add some types that implement the `Draw` trait. We’ll provide the
134`Button` type. Again, actually implementing a GUI library is beyond the scope
135of this book, so the `draw` method won’t have any useful implementation in its
136body. To imagine what the implementation might look like, a `Button` struct
137might have fields for `width`, `height`, and `label`, as shown in Listing 17-7:
138
139<span class="filename">Filename: src/lib.rs</span>
140
fc512014 141```rust,noplayground
74b04a01 142{{#rustdoc_include ../listings/ch17-oop/listing-17-07/src/lib.rs:here}}
13cf67c4
XL
143```
144
145<span class="caption">Listing 17-7: A `Button` struct that implements the
146`Draw` trait</span>
147
148The `width`, `height`, and `label` fields on `Button` will differ from the
149fields on other components, such as a `TextField` type, that might have those
150fields plus a `placeholder` field instead. Each of the types we want to draw on
151the screen will implement the `Draw` trait but will use different code in the
152`draw` method to define how to draw that particular type, as `Button` has here
153(without the actual GUI code, which is beyond the scope of this chapter). The
154`Button` type, for instance, might have an additional `impl` block containing
155methods related to what happens when a user clicks the button. These kinds of
156methods won’t apply to types like `TextField`.
157
158If someone using our library decides to implement a `SelectBox` struct that has
159`width`, `height`, and `options` fields, they implement the `Draw` trait on the
160`SelectBox` type as well, as shown in Listing 17-8:
161
162<span class="filename">Filename: src/main.rs</span>
163
164```rust,ignore
74b04a01 165{{#rustdoc_include ../listings/ch17-oop/listing-17-08/src/main.rs:here}}
13cf67c4
XL
166```
167
168<span class="caption">Listing 17-8: Another crate using `gui` and implementing
169the `Draw` trait on a `SelectBox` struct</span>
170
171Our library’s user can now write their `main` function to create a `Screen`
172instance. To the `Screen` instance, they can add a `SelectBox` and a `Button`
173by putting each in a `Box<T>` to become a trait object. They can then call the
174`run` method on the `Screen` instance, which will call `draw` on each of the
175components. Listing 17-9 shows this implementation:
176
177<span class="filename">Filename: src/main.rs</span>
178
179```rust,ignore
74b04a01 180{{#rustdoc_include ../listings/ch17-oop/listing-17-09/src/main.rs:here}}
13cf67c4
XL
181```
182
183<span class="caption">Listing 17-9: Using trait objects to store values of
184different types that implement the same trait</span>
185
186When we wrote the library, we didn’t know that someone might add the
187`SelectBox` type, but our `Screen` implementation was able to operate on the
9fa01778 188new type and draw it because `SelectBox` implements the `Draw` trait, which
13cf67c4
XL
189means it implements the `draw` method.
190
191This concept—of being concerned only with the messages a value responds to
e74abb32
XL
192rather than the value’s concrete type—is similar to the concept of *duck
193typing* in dynamically typed languages: if it walks like a duck and quacks
194like a duck, then it must be a duck! In the implementation of `run` on `Screen`
195in Listing 17-5, `run` doesn’t need to know what the concrete type of each
196component is. It doesn’t check whether a component is an instance of a `Button`
197or a `SelectBox`, it just calls the `draw` method on the component. By
198specifying `Box<dyn Draw>` as the type of the values in the `components`
199vector, we’ve defined `Screen` to need values that we can call the `draw`
200method on.
13cf67c4
XL
201
202The advantage of using trait objects and Rust’s type system to write code
203similar to code using duck typing is that we never have to check whether a
204value implements a particular method at runtime or worry about getting errors
205if a value doesn’t implement a method but we call it anyway. Rust won’t compile
206our code if the values don’t implement the traits that the trait objects need.
207
208For example, Listing 17-10 shows what happens if we try to create a `Screen`
209with a `String` as a component:
210
211<span class="filename">Filename: src/main.rs</span>
212
213```rust,ignore,does_not_compile
74b04a01 214{{#rustdoc_include ../listings/ch17-oop/listing-17-10/src/main.rs}}
13cf67c4
XL
215```
216
217<span class="caption">Listing 17-10: Attempting to use a type that doesn’t
218implement the trait object’s trait</span>
219
220We’ll get this error because `String` doesn’t implement the `Draw` trait:
221
f035d41b 222```console
74b04a01 223{{#include ../listings/ch17-oop/listing-17-10/output.txt}}
13cf67c4
XL
224```
225
226This error lets us know that either we’re passing something to `Screen` we
227didn’t mean to pass and we should pass a different type or we should implement
228`Draw` on `String` so that `Screen` is able to call `draw` on it.
229
230### Trait Objects Perform Dynamic Dispatch
231
dc9dc135
XL
232Recall in the [“Performance of Code Using
233Generics”][performance-of-code-using-generics]<!-- ignore --> section in
234Chapter 10 our discussion on the monomorphization process performed by the
235compiler when we use trait bounds on generics: the compiler generates
236nongeneric implementations of functions and methods for each concrete type
237that we use in place of a generic type parameter. The code that results from
238monomorphization is doing *static dispatch*, which is when the compiler knows
239what method you’re calling at compile time. This is opposed to *dynamic
240dispatch*, which is when the compiler can’t tell at compile time which method
241you’re calling. In dynamic dispatch cases, the compiler emits code that at
242runtime will figure out which method to call.
13cf67c4
XL
243
244When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t
245know all the types that might be used with the code that is using trait
246objects, so it doesn’t know which method implemented on which type to call.
247Instead, at runtime, Rust uses the pointers inside the trait object to know
248which method to call. There is a runtime cost when this lookup happens that
249doesn’t occur with static dispatch. Dynamic dispatch also prevents the compiler
250from choosing to inline a method’s code, which in turn prevents some
251optimizations. However, we did get extra flexibility in the code that we wrote
252in Listing 17-5 and were able to support in Listing 17-9, so it’s a trade-off
253to consider.
254
255### Object Safety Is Required for Trait Objects
256
257You can only make *object-safe* traits into trait objects. Some complex rules
258govern all the properties that make a trait object safe, but in practice, only
259two rules are relevant. A trait is object safe if all the methods defined in
260the trait have the following properties:
261
262* The return type isn’t `Self`.
263* There are no generic type parameters.
264
265The `Self` keyword is an alias for the type we’re implementing the traits or
266methods on. Trait objects must be object safe because once you’ve used a trait
267object, Rust no longer knows the concrete type that’s implementing that trait.
268If a trait method returns the concrete `Self` type, but a trait object forgets
269the exact type that `Self` is, there is no way the method can use the original
270concrete type. The same is true of generic type parameters that are filled in
271with concrete type parameters when the trait is used: the concrete types become
272part of the type that implements the trait. When the type is forgotten through
273the use of a trait object, there is no way to know what types to fill in the
274generic type parameters with.
275
276An example of a trait whose methods are not object safe is the standard
277library’s `Clone` trait. The signature for the `clone` method in the `Clone`
278trait looks like this:
279
280```rust
281pub trait Clone {
282 fn clone(&self) -> Self;
283}
284```
285
286The `String` type implements the `Clone` trait, and when we call the `clone`
287method on an instance of `String` we get back an instance of `String`.
9fa01778
XL
288Similarly, if we call `clone` on an instance of `Vec<T>`, we get back an
289instance of `Vec<T>`. The signature of `clone` needs to know what type will
290stand in for `Self`, because that’s the return type.
13cf67c4
XL
291
292The compiler will indicate when you’re trying to do something that violates the
293rules of object safety in regard to trait objects. For example, let’s say we
294tried to implement the `Screen` struct in Listing 17-4 to hold types that
295implement the `Clone` trait instead of the `Draw` trait, like this:
296
297```rust,ignore,does_not_compile
74b04a01 298{{#rustdoc_include ../listings/ch17-oop/no-listing-01-trait-object-of-clone/src/lib.rs}}
13cf67c4
XL
299```
300
301We would get this error:
302
f035d41b 303```console
74b04a01 304{{#include ../listings/ch17-oop/no-listing-01-trait-object-of-clone/output.txt}}
13cf67c4
XL
305```
306
307This error means you can’t use this trait as a trait object in this way. If
136023e0
XL
308you’re interested in more details on object safety, see [Rust RFC 255] or check the
309object safety section in the [Rust Reference][object-safety-reference].
13cf67c4
XL
310
311[Rust RFC 255]: https://github.com/rust-lang/rfcs/blob/master/text/0255-object-safety.md
9fa01778
XL
312
313[performance-of-code-using-generics]:
314ch10-01-syntax.html#performance-of-code-using-generics
315[dynamically-sized]: ch19-04-advanced-types.html#dynamically-sized-types-and-the-sized-trait
136023e0 316[object-safety-reference]: ../reference/items/traits.html#object-safety