Skip to main content

Welcome to a Grasp lesson

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

Lesson 8

Implementing Generic Traits

Recommended resources

Welcome back! In our previous lesson, we explored how Rust uses traits to define shared behavior, drawing a parallel to the concept of interfaces in languages like C++. You learned to define traits, implement them for your structs, and use features like default implementations and the #[derive] attribute.

Today, we'll build directly upon that foundation. This lesson combines the power of traits with another fundamental Rust feature: generics. We'll learn how to write functions and data structures that can work with many different types in a safe and efficient manner. The key to this is using trait bounds to tell the compiler what capabilities a generic type must have. This is how Rust achieves powerful, compile-time polymorphism, a concept central to writing abstract and reusable code—a skill that is especially valuable in a domain like embedded systems, where you often want to write driver code that is generic over different hardware peripherals.

From Duplication to Abstraction with Generics

Imagine you need to write a function to find the largest item in a list. If you were only dealing with integers, this would be straightforward. But what if you then needed to find the largest character in a list of chars? You'd have to write another, nearly identical function. This is a classic case of code duplication that generics are designed to solve.

Generics allow us to write code that operates on abstract "placeholder" types, which are then filled in with concrete types by the compiler.

Rust: Generics, Traits, Lifetimes

This video from "The Dev Method" provides an excellent introduction to this exact problem. It starts by showing two separate functions, largest_i32 and largest_char, and then refactors them into a single generic function.

Watch the segment from "removing duplication", which shows how functions can be used to abstract away repetitive logic and then how generics can take this a step further.

So, we can define a single generic function largest<T> that should work for any type T. But how does the compiler know that it can compare two values of type T using the > operator? The short answer is: it doesn't, unless we tell it.


Constraining Generics with Trait Bounds

When you try to compile a generic function like largest<T>, you'll encounter a compiler error. The compiler is telling you that the generic type T doesn't have a known behavior for comparison. This is where the traits you learned about in the last lesson become essential. We can use a trait bound to guarantee to the compiler that any type T used with our function must implement the necessary trait for comparison. In Rust, this is the PartialOrd trait.

Rust: Generics, Traits, Lifetimes

The same video continues to walk through this exact scenario, showing the compiler error and explaining how to fix it by adding a trait bound.

Watch the next part of the video, from the compiler error to the explanation of the PartialOrd trait. This is the core concept of this lesson.

The syntax fn largest<T: PartialOrd>(...) tells the compiler: "This function works for any type T, as long as T implements the PartialOrd trait." This is static dispatch: the checks happen at compile time, ensuring type safety without any runtime overhead. This is a fundamental difference from the dynamic dispatch (dyn Trait) we briefly touched on in the last lesson.


The Many Forms of Trait Bounds

Rust provides several ways to specify trait bounds, giving you flexibility and allowing you to keep your code readable even when the requirements become complex. Let's walk through the different syntaxes.

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

This chapter of the official Rust book provides a comprehensive guide to the syntax of trait bounds.

Please read through the following sections to understand the different ways you can write generic functions that use traits: Start with the section that introduces the impl Trait syntax. This is a concise way to specify a trait bound for a function parameter. Next, read the section on Trait Bound Syntax. This introduces the full <T: Trait> syntax, which is more verbose but also more powerful, especially when you need to ensure multiple parameters have the same generic type. Continue to the section on Multiple Trait Bounds, which shows how to require a type to implement more than one trait using the + operator. Finally, read about where Clauses. This syntax is extremely useful for improving the readability of functions with multiple generic types and complex bounds.

To summarize the key syntaxes:

  • impl Trait: fn notify(item: &impl Summary)
    • Concise and good for simple cases.
  • Trait Bound: fn notify<T: Summary>(item: &T)
    • The fundamental, more explicit form. Required when you need to name the generic type.
  • Multiple Bounds: fn notify<T: Summary + Display>(item: &T)
    • Use + to chain required traits.
  • where Clause:
    fn some_function<T, U>(t: &T, u: &U)
        where T: Display + Clone,
              U: Clone + Debug
    { /* ... */ }
    
    • Moves the bounds out of the main signature, making it much easier to read.

Generics in Structs and Enums

Generics aren't limited to functions. You can also define your own generic data structures. You've already used some of them, like Vec<T>, Option<T>, and Result<T, E>.

Let's see how to define a generic Point<T> struct that can hold coordinates of any type.

Rust: Generics, Traits, Lifetimes

"The Dev Method" video has a clear explanation of how to define and use generic structs, and how to implement methods for them.

First, watch the segment on generic structs. This shows how to define a Point<T> and explains why the types must be consistent. It also looks at the definitions of Option<T> and Result<T, E>. Next, watch the following segment on implementing methods for generic structs. Pay attention to how the impl<T> block mirrors the struct's generic parameter.

As you saw, when you implement methods for a generic struct, you declare the generic parameter T right after the impl keyword. This makes T available to use within the implementation block.

struct Point<T> {
    x: T,
    y: T,
}

impl<T> Point<T> {
    fn x(&self) -> &T {
        &self.x
    }
}

Conditional Methods with Trait Bounds

Now, let's combine these ideas. What if we want a generic struct to have some methods that are always available, but other methods that are only available if the generic type T meets certain criteria? We can do this by adding trait bounds to the impl block itself.

This is an incredibly powerful feature for API design. For example, a Point<T> might have a distance_from_origin method, but that method should only exist if T is a floating-point number.

Traits in Rust

The "Let's Get Rusty" channel has a fantastic, concise explanation of this concept using a Pair<T> struct.

Watch the section on conditionally implementing methods. Notice how there are two impl blocks: one impl<T> Pair<T> for the new method that's always available, and a second impl<T: Display + PartialOrd> Pair<T> for the cmp_display method, which is only available for types that can be displayed and compared.

This pattern allows you to build up functionality in layers, providing a rich API that adapts to the capabilities of the types it contains, all checked at compile time.


Case Study: A Bridge to Embedded Rust

This might all seem a bit abstract, but it is the bedrock of reusable code in the Rust ecosystem, especially in embedded development. The embedded-hal (Hardware Abstraction Layer) crate is a perfect example. It defines a set of traits for common embedded peripherals like I2C, SPI, and GPIO pins.

Device drivers are then written using generic functions that are constrained by these embedded-hal traits. This allows a single driver for, say, an OLED display, to work on dozens of different microcontrollers without changing a single line of code.

Let's look at a concrete example from an article that explores this idea.

Adventures in abstraction with Rust's embedded-hal

This article demonstrates the power of generics and traits by building a small application that can run on both a Raspberry Pi (Linux) and an STM32 microcontroller.

First, look at the code in the section "Common I2C layer". Notice the function signature: pub fn life_i2c<DI: WriteOnlyDataCommand>(interface: DI) -> !. This is exactly what we've been learning! It's a generic function that will accept any type DI, as long as that type implements the WriteOnlyDataCommand trait. Now, skim the next two sections, "I2C on Linux" and "STM32". You don't need to understand all the setup code. The key takeaway is that the same generic function, life_hal::life_i2c, is called in both cases. On Linux, it's called with an I2cdev struct, and on the STM32, it's called with a BlockingI2c struct. Both of these structs implement the WriteOnlyDataCommand trait, so the generic function happily accepts them.

This example directly ties into your goal of mastering Embedded Rust. It shows that understanding generics and trait bounds isn't just an academic exercise; it's the key to unlocking the modular and reusable architecture that makes the Rust embedded ecosystem so powerful.


Conclusion

In this lesson, we've connected the concepts of traits and generics to unlock one of Rust's most powerful abstraction mechanisms. You can now write code that is both highly generic and perfectly type-safe.

Here are the key takeaways:

  • Generics (<T>) allow you to write functions and data structures that work on abstract types, avoiding code duplication.
  • Trait bounds (<T: Trait>) are used to constrain generic types, specifying the behavior (methods) that a type must have. This enables static polymorphism, where all checks are performed at compile time.
  • Rust provides flexible syntax for trait bounds, including impl Trait, the + operator for multiple bounds, and where clauses for improved readability.
  • You can define generic structs and enums, and you can conditionally implement methods on them based on the traits implemented by their generic type parameters.
  • This pattern of generics plus trait bounds is the foundation for writing reusable libraries and drivers, particularly in the embedded space.

In our next lesson, we will look at another fundamental generic type provided by the standard library: the Option enum. You'll learn how to use it to handle the potential absence of a value in a safe and idiomatic way, further building your toolkit for writing robust Rust programs.