Exploring Polymorphism with Traits
Exploring Polymorphism with Traits
Hello! In this lesson, we will explore the concept of polymorphism in Rust using traits. Polymorphism is a core concept in object-oriented programming that allows you to define a single interface and have multiple implementations. In Rust, traits let us achieve polymorphism, enabling different types to be treated uniformly based on shared behavior.
Our journey will involve defining traits, implementing them for different structs, and leveraging these traits to perform polymorphic operations. This lesson will build upon your understanding of traits from the previous lesson and elevate your ability to design flexible and reusable code in Rust.
Let's get started!
Default Methods in Traits
Default methods in traits define method behavior that should be used when a struct that implements the trait does not have a required method. For example, let's say we want to create a new trait named Shape. Any struct that implements the Shape trait should have an area method and print method. However, if a struct that implements Shape does not have a print method, we can provide a default print method within the trait declaration. If the struct does have a print method, that method is used instead of the default method provided in the trait. Let's take a look:
Any struct that implements the Shape trait must provide an implementation for area, but if they do not provide an implementation for print, a default is provided.
Creating structs using Default Methods
Now let's see how these default methods work in action. We'll start by creating a Circle and Rectangle struct. Both will implement the Shape trait by having the required area method. However, we will not give the Circle struct a print method, so it must use the default method. For the Rectangle struct, we use a concept called method overriding. The print method for Rectangle is said to "override" the default print method.
- We've defined a trait named
Shapewith two methods:areaandprint. Theprintmethod has a default implementation - We also defined two structs,
CircleandRectanglethat implement theShapetrait - The
Circlestruct contains anareamethod but not aprintmethod - The
Rectanglestruct contains anareamethod and aprintmethod
Let's take a look at these methods in action:
