Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 7

Implementing Traits for Custom Types

Recommended resources

Welcome to the second module of our Rust journey. In the last lesson, we concluded our exploration of Rust's fundamentals by mastering error handling with the Result enum and the ? operator. We briefly encountered the From trait, which the ? operator uses for automatic error conversion. That was your first glimpse into one of Rust's most powerful abstraction mechanisms.

Today, we dive deep into this concept. This lesson introduces traits, which are at the very heart of Rust's design philosophy. We will learn how to define a trait to specify a set of behaviors and then implement that trait for our custom data types, like structs. For someone with your background in C++ and OOP, you can think of traits as being similar to interfaces or abstract base classes, but as you'll see, Rust's approach offers a unique and powerful take on polymorphism and code reuse. This is the cornerstone for writing abstract, reusable, and idiomatic Rust code.

Defining Shared Behavior

Imagine you are building a media aggregator application. You might have several different types of content, such as a NewsArticle and a SocialPost. While these are distinct data structures, you might want them to share a common behavior: the ability to be summarized. A trait is how you define this shared behavior in Rust.

A trait is a collection of method signatures that define a set of behaviors. It's like a contract: any type that implements the trait promises to provide concrete implementations for its methods.

Traits in Rust

To start, this video from the "Let's Get Rusty" channel introduces the core idea behind traits using the exact scenario of summarizing news articles and tweets.

Watch the initial segment, from the beginning until the explanation of what a trait allows you to do.

Now, let's see how to formally define a trait and implement it for our types. We'll follow the Summary example from the official Rust book.

Traits: Defining Shared Behavior - The Rust Programming ...

This chapter from "The Rust Programming Language" provides the foundational syntax and concepts for working with traits.

First, read the introduction and the section on defining a trait. This will show you the trait keyword and how to declare a method signature. Next, read the section on implementing a trait. This demonstrates the impl Summary for NewsArticle syntax, where you provide the actual code for the summarize method. Finally, pay close attention to the "orphan rule" at the end of that section. This is a key aspect of Rust's design that ensures coherence and prevents conflicts between libraries.

To summarize the core syntax:

  1. Define the trait: You declare the interface with the trait keyword.
    pub trait Summary {
        fn summarize(&self) -> String;
    }
    
  2. Implement the trait: For each type, you use an impl Trait for Type block to provide the specific behavior.
    pub struct NewsArticle { /* fields */ }
    
    impl Summary for NewsArticle {
        fn summarize(&self) -> String {
            // implementation specific to NewsArticle
            format!("{}, by {}", self.headline, self.author)
        }
    }
    

Traits vs. C++ Inheritance

With your C++ background, you might be tempted to equate traits with inheritance from a pure virtual base class. While they serve a similar purpose in achieving polymorphism, Rust's approach is fundamentally different and is often described as "composition over inheritance."

In C++, an object's type is tied to a rigid class hierarchy. In Rust, a struct is a simple data container. Its capabilities are defined by the collection of traits it implements. A type can implement any number of traits, allowing you to mix and match behaviors in a way that is much more flexible than multiple inheritance.

Understanding Rust as a C++ developer

This article, written for C++ developers, directly contrasts the two approaches.

Read the section titled "Inheritance vs. traits". Notice the key phrase: "There is no inheritance (or overloading) in Rust, but it’s possible to extend the implementation with a so called trait".

The article mentions dyn Trait, which stands for "dynamic dispatch". This is how Rust achieves runtime polymorphism. It tells the compiler that the specific type won't be known until runtime, so method calls must go through a virtual method table (a vtable), which is exactly how C++ virtual functions work.

Here is a visual example. We have a Draw trait and two structs, Circle and Square, that both implement it. We can then create a vector that holds different shapes, all of which are treated as "drawable" things.

In this example, both `Circle` and `Square` implement the `Draw` trait. This allows us to create a `Vec<Box<dyn Draw>>`, a collection of different concrete types that all share the `Draw` behavior.

This is runtime polymorphism in action. The for loop doesn't need to know whether shape is a Circle or a Square; it only knows that it's something that implements Draw, and therefore has a .draw() method it can call.


Default Implementations

Traits can become even more powerful by providing default behavior for their methods. This means you can define a method's implementation directly inside the trait definition. Types that implement the trait can then either use this default behavior for free or override it with a custom implementation.

This is useful for reducing boilerplate code. A trait can even provide a default implementation for one method that calls another method required by the same trait. This allows you to provide a rich functional skeleton, requiring implementors to only fill in a few key details.

Traits in Rust

The same "Let's Get Rusty" video demonstrates this feature clearly.

Watch the section on default implementations. It first shows a simple default and then demonstrates the more advanced pattern of a default method calling a non-default method within the same trait.


Commonly Used Standard Library Traits

You don't always have to write your own traits. The Rust standard library comes with many useful traits that are used throughout the ecosystem. We have already seen Copy (for types that can be bitwise copied) and From (for conversions).

Another ubiquitous trait is Debug. Implementing the Debug trait for your type allows it to be printed using the {:?} or {:#?} format specifiers in println!, which is incredibly useful for debugging.

While you can implement Debug manually, the compiler can usually generate a sensible default implementation for you if you ask it to. This is done with the derive attribute.




#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 10, y: 20 };
    println!("My point is: {:?}", p); // Output: My point is: Point { x: 10, y: 20 }
}

The #[derive(Debug)] line tells the compiler to automatically generate the code for impl Debug for Point.

This diagram shows the definition of the `Debug` trait and a template for a manual implementation. However, as noted in the "Can be derived" box, using `#[derive(Debug)]` is usually the easiest approach.

Many other standard traits can be derived, including Clone, Copy, PartialEq, and Eq. You will see the derive attribute used extensively in Rust code.


Conclusion

In this lesson, we've pulled back the curtain on one of Rust's core features for abstraction. You now have the foundational knowledge to define and implement your own traits, which is a significant step towards writing clean, modular, and reusable Rust code.

Here are the key takeaways:

  • Traits define shared behavior by specifying a set of method signatures that a type must implement.
  • You define a trait with the trait keyword and implement it for a type using the impl Trait for Type syntax.
  • Traits are Rust's mechanism for achieving polymorphism, favoring a flexible composition-based approach over the rigid inheritance hierarchies found in languages like C++.
  • Default implementations can be provided within a trait definition to reduce boilerplate and provide reusable functionality.
  • The standard library provides many useful traits like Debug, which can often be implemented automatically using the #[derive] attribute.

We've laid the groundwork for abstraction. In our next lesson, we will build directly on this foundation to explore generics. We'll learn how to write functions and data structures that use traits to operate on many different types in a safe and efficient way. This is where you'll see the true power of combining traits and generics to write highly expressive code.