Course contentsShow
← Rust
Lesson 672 of 1,9106. Generics and Static DispatchFree lesson

Parametric Polymorphism Explained

Define and implement functions that work across multiple types using type parameters.

In this lesson, you will learn how to write flexible, reusable code that works across multiple data types using parametric polymorphism, or "Generics."

The Problem of Specificity

So far, we have built systems using concrete types. If you wanted a function to log an integer, you wrote a function for i32. If you wanted to log a string, you wrote another for &str. This creates code duplication and limits the flexibility of your system components. Parametric polymorphism allows you to define a function "parameterized" by a type, letting the logic stay the same while the data type changes.

Implementing Generics

In Rust, we introduce a type parameter using angle brackets <T>. The letter T is a placeholder, short for "Type." When you use T in your function signature, you are telling the compiler: "This function accepts any type, as long as it is consistent within the function body."

Consider a simple identity function:

fn show_me<T>(value: T) {
    println!("Received: {:?}", value);
}

In this example, <T> declares the generic type parameter. When you call show_me(5), the compiler realizes T is i32. If you call show_me("Hello"), T becomes &str.

Why Use This?

By using generics, we decouple our logic from specific data types. This is essential when building tools like the component registries or data-oriented pipelines we discussed earlier. Instead of creating a ComponentRegistry for every single type of struct in your system, you can write one Registry<T> and reuse it throughout your entire architecture.

It keeps your code DRY (Don't Repeat Yourself) while maintaining Rust's strict type safety. Even though the type is "parameterized," the compiler still ensures that the operations you perform on T are valid for the specific type passed in.

Key Takeaway: Parametric polymorphism allows you to write one function or struct that works for any type, reducing code duplication while preserving the compile-time type safety that keeps your system robust.