7 Using traits, generics, and structs for specialized tasks

 

This chapter covers

  • Using const generics
  • Applying traits to external crate types
  • Extending types with extension traits
  • Implementing blanket traits
  • Using marker traits to mark types with attributes
  • Tagging with structs
  • Providing access to internal data with reference objects

The previous chapters introduced several Rust advanced techniques. This chapter expands on some of those themes and explores more advanced design patterns. These patterns are useful in many circumstances, but you’ll likely use them less frequently because they are more complex to implement and often apply to scenarios that you may not encounter often.

To use an analogy, the patterns discussed in the previous chapters describe standard tools you might find in every toolbox that can be used for a wide variety of jobs: hammer, pliers, screwdriver, power drill, and so on. The patterns discussed in this chapter are for more specialized jobs, such as the woodworking tools you would find in a wood shop: table saw, planer, lathe, band saw, and so on. Although these patterns are less useful for everyday Rust programming, it’s good to explore them so that you’ll know how to use them when you need them.

7.1 Const generics

7.2 Implementing traits for external crate types

7.2.1 Wrapper structs

7.2.2 Using Deref to unwrap a wrapped struct

7.3 Extension traits

7.4 Blanket traits

7.5 Marker traits

7.6 Struct tagging

7.7 Reference objects

Summary