-
Book Overview & Buying
-
Table Of Contents
Design Patterns and Best Practices in Rust
By :
In this section, we will discuss Rust traits and how they can be prone to being misused when designing in Rust. Traits exist to provide contracts that structs can fulfil, which adds expressiveness and flexibility to the language. However, we will see why they are not a substitute for interfaces or abstract classes in the OO sense.
As we discussed in the previous section, Rust traits, while similar to interfaces or pure abstract classes, do not actually provide or represent the same kind of type hierarchy as classes, and polymorphism using traits is more circumscribed and less convenient and natural in Rust. It is tempting to reach for traits as a way to model inheritance, or to try to use them to design systems that center dynamic polymorphism, but they are not usually the optimal way to design in Rust, or to create solutions to challenges we will encounter.
In the previous chapter, we began creating the Bad Calculator project. Let's examine how we can...