Using Trait Objects that Allow for Values of Different Types (original) (raw)

  1. Foreword
  2. Introduction
  3. 1. Getting Started
    1. 1.1. Installation
    2. 1.2. Hello, World!
    3. 1.3. Hello, Cargo!
  4. 2. Programming a Guessing Game
  5. 3. Common Programming Concepts
    1. 3.1. Variables and Mutability
    2. 3.2. Data Types
    3. 3.3. How Functions Work
    4. 3.4. Comments
    5. 3.5. Control Flow
  6. 4. Understanding Ownership
    1. 4.1. What is Ownership?
    2. 4.2. References & Borrowing
    3. 4.3. Slices
  7. 5. Using Structs to Structure Related Data
    1. 5.1. Defining and Instantiating Structs
  8. 5.2. An Example Program Using Structs
  9. 5.3. Method Syntax
  10. 6. Enums and Pattern Matching
    1. 6.1. Defining an Enum
  11. 6.2. The match Control Flow Operator
  12. 6.3. Concise Control Flow with if let
  13. 7. Packages, Crates, and Modules
    1. 7.1. Packages and crates for making libraries and executables
  14. 7.2. Modules and use to control scope and privacy
  15. 8. Common Collections
    1. 8.1. Vectors
  16. 8.2. Strings
  17. 8.3. Hash Maps
  18. 9. Error Handling
    1. 9.1. Unrecoverable Errors with panic!
  19. 9.2. Recoverable Errors with Result
  20. 9.3. To panic! or Not To panic!
  21. 10. Generic Types, Traits, and Lifetimes
    1. 10.1. Generic Data Types
  22. 10.2. Traits: Defining Shared Behavior
  23. 10.3. Validating References with Lifetimes
  24. 11. Testing
    1. 11.1. Writing tests
  25. 11.2. Running tests
  26. 11.3. Test Organization
  27. 12. An I/O Project: Building a Command Line Program
    1. 12.1. Accepting Command Line Arguments
  28. 12.2. Reading a File
  29. 12.3. Refactoring to Improve Modularity and Error Handling
  30. 12.4. Developing the Library’s Functionality with Test Driven Development
  31. 12.5. Working with Environment Variables
  32. 12.6. Writing Error Messages to Standard Error Instead of Standard Output
  33. 13. Functional Language Features: Iterators and Closures
    1. 13.1. Closures: Anonymous Functions that Can Capture Their Environment
  34. 13.2. Processing a Series of Items with Iterators
  35. 13.3. Improving Our I/O Project
  36. 13.4. Comparing Performance: Loops vs. Iterators
  37. 14. More about Cargo and Crates.io
    1. 14.1. Customizing Builds with Release Profiles
  38. 14.2. Publishing a Crate to Crates.io
  39. 14.3. Cargo Workspaces
  40. 14.4. Installing Binaries from Crates.io with cargo install
  41. 14.5. Extending Cargo with Custom Commands
  42. 15. Smart Pointers
    1. 15.1. Box Points to Data on the Heap and Has a Known Size
  43. 15.2. The Deref Trait Allows Access to the Data Through a Reference
  44. 15.3. The Drop Trait Runs Code on Cleanup
  45. 15.4. Rc, the Reference Counted Smart Pointer
  46. 15.5. RefCell and the Interior Mutability Pattern
  47. 15.6. Creating Reference Cycles and Leaking Memory is Safe
  48. 16. Fearless Concurrency
    1. 16.1. Threads
  49. 16.2. Message Passing
  50. 16.3. Shared State
  51. 16.4. Extensible Concurrency: Sync and Send
  52. 17. Object Oriented Programming Features of Rust
    1. 17.1. Characteristics of Object-Oriented Languages
  53. 17.2. Using Trait Objects that Allow for Values of Different Types
  54. 17.3. Implementing an Object-Oriented Design Pattern
  55. 18. Patterns Match the Structure of Values
    1. 18.1. All the Places Patterns May be Used
  56. 18.2. Refutability: Whether a Pattern Might Fail to Match
  57. 18.3. All the Pattern Syntax
  58. 19. Advanced Features
    1. 19.1. Unsafe Rust
  59. 19.2. Advanced Lifetimes
  60. 19.3. Advanced Traits
  61. 19.4. Advanced Types
  62. 19.5. Advanced Functions & Closures
  63. 19.6. Macros
  64. 20. Final Project: Building a Multithreaded Web Server
    1. 20.1. A Single Threaded Web Server
  65. 20.2. Turning our Single Threaded Server into a Multithreaded Server
  66. 20.3. Graceful Shutdown and Cleanup
  67. 21. Appendix
    1. 21.1. A - Keywords
  68. 21.2. B - Operators and Symbols
  69. 21.3. C - Derivable Traits
  70. 21.4. D - Useful Development Tools
  71. 21.5. E - Editions
  72. 21.6. F - Translations
  73. 21.7. G - How Rust is Made and “Nightly Rust”

The Rust Programming Language

Using Trait Objects that Allow for Values of Different Types

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-10 where we defined a SpreadsheetCell enum 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. 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 draw method on each one to draw it to the screen—a common technique for GUI tools. We’ll create a library crate calledgui that contains the structure of a GUI library. This crate might include some types for people to use, such as Button or TextField. In addition,gui users will want to create their own types that can be drawn: for instance, one programmer might add an Image and 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 gui needs to keep track of many values of different types, and it needs to call a draw method on each of these differently typed values. It doesn’t need to know exactly what will happen when we call the draw method, just that the value will have that method available for us to call.

To do this in a language with inheritance, we might define a class namedComponent that has a method named draw on it. The other classes, such asButton, Image, and SelectBox, would inherit from Component and thus inherit the draw method. They could each override the draw method to define their custom behavior, but the framework could treat all of the types as if they were Component instances and call draw on them. But because Rust doesn’t have inheritance, we need another way to structure the gui library to allow users to extend it with new types.

Defining a Trait for Common Behavior

To implement the behavior we want gui to have, we’ll define a trait namedDraw that will have one method named draw. Then we can define a vector that takes a trait object. A trait object points to an instance of a type that implements the trait we specify. We create a trait object by specifying some sort of pointer, such as a & reference or a Box<T> smart pointer, and then specifying the relevant trait, and add a dyn keyword. (We’ll talk about the reason trait objects must use a pointer in Chapter 19 in the section “Dynamically Sized Types & Sized”.) 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 impl blocks 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 nameddraw:

Filename: src/lib.rs


# #![allow(unused_variables)]
#fn main() {
pub trait Draw {
    fn draw(&self);
}
#}

Listing 17-3: Definition of the Draw trait

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 namedScreen that holds a vector named components. This vector is of typeBox<dyn Draw>, which is a trait object; it’s a stand-in for any type inside a Box that implements the Draw trait.

Filename: src/lib.rs


# #![allow(unused_variables)]
#fn main() {
# pub trait Draw {
#     fn draw(&self);
# }
#
pub struct Screen {
    pub components: Vec<Box<dyn Draw>>,
}
#}

Listing 17-4: Definition of the Screen struct with acomponents field holding a vector of trait objects that implement the Drawtrait

On the Screen struct, we’ll define a method named run that will call thedraw method on each of its components, as shown in Listing 17-5:

Filename: src/lib.rs


# #![allow(unused_variables)]
#fn main() {
# 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();
        }
    }
}
#}

Listing 17-5: A run method on Screen that calls thedraw method on each component

This works differently than 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 Screen struct using a generic type and a trait bound as in Listing 17-6:

Filename: src/lib.rs


# #![allow(unused_variables)]
#fn main() {
# 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();
        }
    }
}
#}

Listing 17-6: An alternate implementation of the Screenstruct and its run method using generics and trait bounds

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 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 add some types that implement the Draw trait. We’ll provide theButton type. Again, actually implementing a GUI library is beyond the scope of this book, so the draw method won’t have any useful implementation in its body. To imagine what the implementation might look like, a Button struct might have fields for width, height, and label, as shown in Listing 17-7:

Filename: src/lib.rs


# #![allow(unused_variables)]
#fn main() {
# pub trait Draw {
#     fn draw(&self);
# }
#
pub struct Button {
    pub width: u32,
    pub height: u32,
    pub label: String,
}

impl Draw for Button {
    fn draw(&self) {
        // code to actually draw a button
    }
}
#}

Listing 17-7: A Button struct that implements theDraw trait

The width, height, and label fields on Button will differ from the fields on other components, such as a TextField type, that might have those fields plus a placeholder field instead. Each of the types we want to draw on the screen will implement the Draw trait but will use different code in thedraw method to define how to draw that particular type, as Button has here (without the actual GUI code, which is beyond the scope of this chapter). TheButton type, for instance, might have an additional impl block 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 haswidth, height, and options fields, they implement the Draw trait on theSelectBox type as well, as shown in Listing 17-8:

Filename: src/main.rs

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
    }
}

Listing 17-8: Another crate using gui and implementing the Draw trait on a SelectBox struct

Our library’s user can now write their main function to create a Screeninstance. To the Screen instance, they can add a SelectBox and a Buttonby putting each in a Box<T> to become a trait object. They can then call therun method on the Screen instance, which will call draw on each of the components. Listing 17-9 shows this implementation:

Filename: src/main.rs

use gui::{Screen, Button};

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();
}

Listing 17-9: Using trait objects to store values of different types that implement the same trait

When we wrote the library, we didn’t know that someone might add theSelectBox type, but our Screen implementation was able to operate on the new type and draw it because SelectBox implements the Draw type, which means it implements the draw method.

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 _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 run on Screen in Listing 17-5, run doesn’t need to know what the concrete type of each component is. It doesn’t check whether a component is an instance of a Button or aSelectBox, it just calls the draw method on the component. By specifyingBox<dyn Draw> as the type of the values in the components vector, we’ve defined Screen to need values that we can call the draw method on.

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 Screenwith a String as a component:

Filename: src/main.rs

use gui::Screen;

fn main() {
    let screen = Screen {
        components: vec![
            Box::new(String::from("Hi")),
        ],
    };

    screen.run();
}

Listing 17-10: Attempting to use a type that doesn’t implement the trait object’s trait

We’ll get this error because String doesn’t implement the Draw trait:

error[E0277]: the trait bound `std:🧵:String: gui::Draw` is not satisfied
  --> src/main.rs:7:13
   |
 7 |             Box::new(String::from("Hi")),
   |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait gui::Draw is not
   implemented for `std:🧵:String`
   |
   = note: required for the cast to the object type `gui::Draw`

This error lets us know that either we’re passing something to Screen we didn’t mean to pass and we should pass a different type or we should implementDraw on String so that Screen is able to call draw on 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 is 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. There is a runtime cost when this lookup happens 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.

Object Safety Is Required for Trait Objects

You can only make object-safe traits into trait objects. Some complex rules govern all the properties that make a trait object safe, but in practice, only two rules are relevant. A trait is object safe if all the methods defined in the trait have the following properties:

The Self keyword is an alias for the type we’re implementing the traits or methods on. Trait objects must be object safe because once you’ve used a trait object, Rust no longer knows the concrete type that’s implementing that trait. If a trait method returns the concrete Self type, but a trait object forgets the exact type that Self is, there is no way the method can use the original concrete type. The same is true of generic type parameters that are filled in with concrete type parameters when the trait is used: the concrete types become part of the type that implements the trait. When the type is forgotten through the use of a trait object, there is no way to know what types to fill in the generic type parameters with.

An example of a trait whose methods are not object safe is the standard library’s Clone trait. The signature for the clone method in the Clonetrait looks like this:


# #![allow(unused_variables)]
#fn main() {
pub trait Clone {
    fn clone(&self) -> Self;
}
#}

The String type implements the Clone trait, and when we call the clonemethod on an instance of String we get back an instance of String. Similarly, if we call clone on an instance of Vec, we get back an instance of Vec. The signature of clone needs to know what type will stand in forSelf, because that’s the return type.

The compiler will indicate when you’re trying to do something that violates the rules of object safety in regard to trait objects. For example, let’s say we tried to implement the Screen struct in Listing 17-4 to hold types that implement the Clone trait instead of the Draw trait, like this:

pub struct Screen {
    pub components: Vec<Box<dyn Clone>>,
}

We would get this error:

error[E0038]: the trait `std::clone::Clone` cannot be made into an object
 --> src/lib.rs:2:5
  |
2 |     pub components: Vec<Box<dyn Clone>>,
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `std::clone::Clone` cannot be
made into an object
  |
  = note: the trait cannot require that `Self : Sized`

This error means you can’t use this trait as a trait object in this way. If you’re interested in more details on object safety, see Rust RFC 255.