Using Trait Objects That Allow for Values of Different Types
- Using Trait Objects That Allow for Values of Different Types
Compare implementing trait with trait bounds and trait objects
-
The Same Trait definition
#![allow(unused)] fn main() { pub trait Draw { fn draw(&self); } } -
Different Call:
Situation Impl Trait Impl pub components: Vec<T> Trait Objects pub components: Vec<Box<dyn Draw>>
one limitation of vectors: only one type
In Chapter 8, we mentioned that one limitation of vectors is that they can store elements of only one type:
- We created a workaround in Listing 8-9 where
we defined a
SpreadsheetCellenum that had variants to hold integers, floats, and text. - This meant we could store different types of data in each cell and still have a vector that represented a row of cells.
- This is a perfectly good solution when our interchangeable items are a fixed set of types that we know when our code is compiled.
However, sometimes we want our library user to be able to extend the set of types that are valid in a particular situation.
How we achieve to extend the set of types
To show how we might achieve this:
- we’ll create an example graphical user interface (GUI) tool that iterates
through a list of items, calling a
drawmethod on each one to draw it to the screen—a common technique for GUI tools. - We’ll create a library crate called
guithat contains the structure of a GUI library. - This crate might include some types for people to use, such as
ButtonorTextField. - In addition,
guiusers will want to create their own types that can be drawn:
for instance, one programmer might add an
Imageand another might add aSelectBox.
- We won’t implement a fully fledged GUI library for this example but will show how the pieces would fit together.
At the time of writing the library, we can’t know and define all the types other programmers might want to create.
But we do know that
guineeds to keep track of many values of different types, and it needs to call adrawmethod on each of these differently typed values. It doesn’t need to know exactly what will happen when we call thedrawmethod, just that the value will have that method available for us to call.
How a language with inheritance do
To do this in a language with inheritance:
- we might define a class named
Componentthat has a method nameddrawon it. - The other classes, such as
Button,Image, andSelectBox, would inherit fromComponentand thus inherit thedrawmethod. - They could each override the
drawmethod to define their custom behavior, but the framework could treat all of the types as if they wereComponentinstances and calldrawon them.
But because Rust doesn’t have inheritance, we need another way to structure the
guilibrary to allow users to extend it with new types.
How a language without inheritance do
Defining a Trait for Common Behavior
To implement the behavior we want gui to have:
- we’ll define a trait named
Drawthat will have one method nameddraw. - Then we can define a vector that takes a trait object.
A trait object points to both an instance of a type implementing our specified trait and a table used to look up trait methods on that type at runtime:
- We create a trait object by specifying some sort of pointer, such as a
&reference or aBox<T>smart pointer - then the
dynkeyword, and then specifying the relevant trait. (We’ll talk about the reason trait objects must use a pointer in Chapter 19 in the section “Dynamically Sized Types and theSizedTrait.”) - We can use trait objects in place of a generic or concrete type.
Wherever we use a trait object, Rust’s type system will ensure at compile time that any value used in that context will implement the trait object’s trait. Consequently, we don’t need to know all the possible types at compile time.
We’ve mentioned that:
- in Rust, we refrain from calling structs and enums “objects” to distinguish them from other languages’ objects.
- In a struct or
enum, the data in the struct fields and the behavior in
implblocks are separated, whereas in other languages, the data and behavior combined into one concept is often labeled an object.
However, trait objects are more like objects in other languages in the sense that they combine data and behavior.
But trait objects differ from traditional objects in that we can’t add data to a trait object.
Trait objects aren’t as generally useful as objects in other languages: their specific purpose is to allow abstraction across common behavior.
Listing 17-3 shows how to define a trait named Draw with one method named
draw:
This syntax should look familiar from our discussions on how to define traits in Chapter 10.
Next comes some new syntax:
- Listing 17-4 defines a struct named
Screenthat holds a vector namedcomponents. - This vector is of type
Box<dyn Draw>, which is a trait object; - it’s a stand-in for any type inside a
Boxthat implements theDrawtrait.
Listing 17-4: Definition of the Screen struct with a components field holding a vector of trait objects that implement the Draw trait
pub trait Draw {
fn draw(&self);
}
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
On the Screen struct, we’ll define a method named run that will call the
draw method on each of its components, as shown in Listing 17-5:
Listing 17-5: A run method on Screen that calls the draw method on each component
pub trait Draw {
fn draw(&self);
}
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
impl Screen {
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
Trait Object works differently from Trait Bounds
This works differently from defining a struct that uses a generic type parameter with trait bounds:
- A generic type parameter can only be substituted with one concrete type at a time
- whereas trait objects allow for multiple concrete types to fill in for the trait object at runtime.
For example, we could have defined the
Screenstruct using a generic type and a trait bound as in Listing 17-6:
Listing 17-6: An alternate implementation of the Screen struct and its run method using generics and trait bounds
pub trait Draw {
fn draw(&self);
}
pub struct Screen<T: Draw> {
pub components: Vec<T>,
}
impl<T> Screen<T>
where
T: Draw,
{
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
This restricts us to a Screen instance that has a list of components all of
type Button or all of type TextField.
If you’ll only ever have homogeneous collections, using generics and trait bounds is preferable because the definitions will be monomorphized at compile time to use the concrete types.
On the other hand, with the method using trait objects, one Screen instance
can hold a Vec<T> that contains a Box<Button> as well as a
Box<TextField>.
Let’s look at how this works, and then we’ll talk about the runtime performance implications.
Implementing the Trait
Now we’ll do these:
- add some types that implement the
Drawtrait - provide the
Buttontype. - Again, actually implementing a GUI library is beyond the scope
of this book, so the
drawmethod won’t have any useful implementation in its body. - To imagine what the implementation might look like, a
Buttonstruct might have fields forwidth,height, andlabel, as shown in Listing 17-7:
- The
width,height, andlabelfields onButtonwill differ from the fields on other components; - for example, a
TextFieldtype might have those same fields plus aplaceholderfield. - Each of the types we want to draw on
the screen will implement the
Drawtrait but will use different code in thedrawmethod to define how to draw that particular type, asButtonhas here (without the actual GUI code, as mentioned). - The
Buttontype, for instance, might have an additionalimplblock containing methods related to what happens when a user clicks the button. - These kinds of methods won’t apply to types like
TextField.
If someone using our library decides to implement a SelectBox struct that has
width, height, and options fields, they implement the Draw trait on the
SelectBox type as well, as shown in Listing 17-8:
Listing 17-8: Another crate using gui and implementing the Draw trait on a SelectBox struct
use gui::Draw;
struct SelectBox {
width: u32,
height: u32,
options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
// code to actually draw a select box
}
}
fn main() {}
- Our library’s user can now write their
mainfunction to create aScreeninstance. - To the
Screeninstance, they can add aSelectBoxand aButtonby putting each in aBox<T>to become a trait object. - They can then call the
runmethod on theScreeninstance, which will calldrawon each of the components.
Listing 17-9 shows this implementation:
Listing 17-9: Using trait objects to store values of different types that implement the same trait
use gui::Draw;
struct SelectBox {
width: u32,
height: u32,
options: Vec<String>,
}
impl Draw for SelectBox {
fn draw(&self) {
// code to actually draw a select box
}
}
use gui::{Button, Screen};
fn main() {
let screen = Screen {
components: vec![
Box::new(SelectBox {
width: 75,
height: 10,
options: vec![
String::from("Yes"),
String::from("Maybe"),
String::from("No"),
],
}),
Box::new(Button {
width: 50,
height: 10,
label: String::from("OK"),
}),
],
};
screen.run();
}
- When we wrote the library, we didn’t know that someone might add the
SelectBoxtype - but our
Screenimplementation was able to operate on the new type and draw it - because
SelectBoximplements theDrawtrait, which means it implements thedrawmethod.
This concept—of being concerned only with the messages a value responds to rather than the value’s concrete type—is similar to the concept of duck typing in dynamically typed languages:
- if it walks like a duck and quacks like a duck, then it must be a duck!
- In the implementation of
runonScreenin Listing 17-5,rundoesn’t need to know what the concrete type of each component is. - It doesn’t check whether a component is an instance of a
Buttonor aSelectBox, it just calls thedrawmethod on the component.
By specifying
Box<dyn Draw>as the type of the values in thecomponentsvector, we’ve definedScreento need values that we can call thedrawmethod on.
The advantace of using trait objects: just like duck typing
The advantage of using trait objects and Rust’s type system to write code similar to code using duck typing is that:
- we never have to check whether a value implements a particular method at runtime
- or worry about getting errors if a value doesn’t implement a method but we call it anyway.
- Rust won’t compile our code if the values don’t implement the traits that the trait objects need.
For example, Listing 17-10 shows what happens if we try to create a Screen
with a String as a component:
Listing 17-10: Attempting to use a type that doesn’t implement the trait object’s trait
use gui::Screen;
fn main() {
let screen = Screen {
components: vec![Box::new(String::from("Hi"))],
};
screen.run();
}
We’ll get this error because String doesn’t implement the Draw trait:
$ cargo run
Compiling gui v0.1.0 (file:///projects/gui)
error[E0277]: the trait bound `String: Draw` is not satisfied
--> src/main.rs:5:26
|
5 | components: vec![Box::new(String::from("Hi"))],
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Draw` is not implemented for `String`
|
= help: the trait `Draw` is implemented for `Button`
= note: required for the cast to the object type `dyn Draw`
For more information about this error, try `rustc --explain E0277`.
error: could not compile `gui` due to previous error
This error lets us know that:
- either we’re passing something to
Screenwe didn’t mean to pass and so should pass a different type - or we should implement
DrawonStringso thatScreenis able to calldrawon it.
Trait Objects Perform Dynamic Dispatch
Recall in the “Performance of Code Using Generics” section in Chapter 10 our discussion on the monomorphization process performed by the compiler when we use trait bounds on generics:
- the compiler generates nongeneric implementations of functions and methods for each concrete type that we use in place of a generic type parameter.
- The code that results from monomorphization is doing static dispatch, which is when the compiler knows what method you’re calling at compile time.
- This is opposed to dynamic dispatch, which is when the compiler can’t tell at compile time which method you’re calling.
- In dynamic dispatch cases, the compiler emits code that at runtime will figure out which method to call.
When we use trait objects, Rust must use dynamic dispatch:
- The compiler doesn’t know all the types that might be used with the code that’s using trait objects, so it doesn’t know which method implemented on which type to call.
- Instead, at runtime, Rust uses the pointers inside the trait object to know which method to call.
- This lookup incurs a runtime cost that doesn’t occur with static dispatch.
- Dynamic dispatch also prevents the compiler from choosing to inline a method’s code, which in turn prevents some optimizations.
However, we did get extra flexibility in the code that we wrote in Listing 17-5 and were able to support in Listing 17-9, so it’s a trade-off to consider.