April 2026
Intermediate
631 pages
16h 20m
English
Both generic types and associated types allow the implementer to decide which concrete types should be used in a trait’s functions and methods. In this section, we explore the circumstances under which each should be used, aiming to clarify when generics are more suitable and when associated types offer a better solution.
Consider an Addition trait with a single add method, as shown in Listing 8.47.
trait Addition { type Rhs; type Output; fn add(self, rhs: Self::Rhs) -> Self::Output;}
Listing 8.47 Defining the Addition Trait with Associated Types of Rhs and Output
This trait will let’s add instances of types self and Rhs using the add method.
Next, define a simple Point struct representing ...
Read now
Unlock full access