April 2026
Intermediate
631 pages
16h 20m
English
In this section, we’ll explore the concept of traits in Rust and how they enable polymorphism. We’ll start by explaining why and how to use traits. Then, we’ll dive into the details, covering topics like default implementations, trait bounds, supertraits, trait objects, derived traits, marker traits, and associated types.
Let’s consider two structures, Square and Rectangle, as shown in Listing 8.14.
struct Square { side: f32, line_width: u8, color: String,}struct Rectangle { length: f32, width: f32, line_width: u8, color: String,}
Listing 8.14 Defining the Struct Square and Rectangle
The Square struct has a field called side, which defines the square’s dimensions. Additionally, this struct ...
Read now
Unlock full access