medium.com 10 min read Original Source

No Classes, No Inheritance. Here’s How Rust Does Polymorphism.

Not a Medium member? Read it here for free

In this article, we’ll explore traits and generics, two pillars of Rust’s type system that enable code reusability, polymorphism, and abstraction. Traits define shared behavior across types, while generics let you write flexible code that works with multiple data types , maintaining peak performance (no kidding , the speed is very real with Rust). Together, they provide a reliable system for Rust’s expressive and safe programming model.

Section 1: Traits — The Behavioral Blueprint

1.1 Trait Fundamentals

Traits define shared interfaces that types can implement, establishing behavioral contracts while preserving zero-cost abstractions.

  • Shared Interfaces:
    Traits allow you to define a set of methods and behaviors that different types must provide. Think of them as contracts: if a type implements a trait, it agrees to offer certain functionality. For instance, a Serializer trait might require methods to serialize data into bytes and to reconstruct an object from those bytes.
  • Behavioral Contracts:
    When you define a trait, you’re specifying what a type must do rather than how it does it. This separation of “what” from “how” enables polymorphism , different types can perform similar actions in their own way while sharing a common interface.
  • Zero-Cost Abstractions:
    Unlike some traditional object-oriented programming (OOP) interfaces, Rust’s traits are designed so that there’s no additional runtime cost. This is achieved via compile-time optimizations like monomorphization, where the compiler generates specialized code for each type that implements the trait.

1.2 Type Cohesion

  • Ensuring Consistency:
    By specifying that a type implements a particular trait, you guarantee that the type adheres to a specific set of behaviors. This helps maintain consistency across your codebase because you know that any type implementing a given trait will provide the necessary functionality.
  • Enhanced Reusability:
    With traits, you can write generic functions that work with any type that implements the trait, without needing to know the details of the type itself. For example, a function that works on any Serializer can call serialize() and rely on the fact that it exists, regardless of the underlying type.
  • Compile-Time Safety:
    Rust checks at compile time that your types correctly implement the traits they claim to. This means that many bugs can be caught early in the development process, reducing runtime errors and ensuring more robust code.

Consider the following trait definition:

Result;

// Instance method: Stop the vehicle.
fn stop(&self);

// Default implementation: Provide a default honk behavior.
// Types can override this if they need special behavior.
fn honk(&self) {
println!("Beep beep!");
}
}

// Concrete type representing a Car.
struct Car {
model: String,
fuel: u8, // Fuel percentage (0 to 100)
}

// Another concrete type representing a Bike.
struct Bike {
brand: String,
electric: bool,
}

// Implement Vehicle for Car.
impl Vehicle for Car {
// Start the car if it has fuel.
fn start(&self) -> Result {
if self.fuel > 0 {
println!("{} is starting…", self.model);
Ok(())
} else {
println!("{} cannot start! Out of fuel.", self.model);
Err(Error::OutOfFuel)
}
}

// Stop the car.
fn stop(&self) {
println!("{} is stopping…", self.model);
}

// Overriding the default honk behavior.
fn honk(&self) {
println!("{} says: Honk honk!", self.model);
}
}

// Implement Vehicle for Bike.
impl Vehicle for Bike {
fn start(&self) -> Result {
if self.electric {
println!("{} is starting silently…", self.brand);
} else {
println!("{} is ready to pedal!", self.brand);
}
Ok(())
}

// Stop the bike.
fn stop(&self) {
println!("{} is slowing down…", self.brand);
}

// Bikes can honk, but let's keep the default behavior.
}

// A function that works with any type that implements the Vehicle trait.
fn drive(vehicle: &T) {
let _ = vehicle.start();
vehicle.honk();
vehicle.stop();
}

fn main() {
let my_car = Car {
model: String::from("Tesla Model S"),
fuel: 80,
};

let my_bike = Bike {
brand: String::from("Giant"),
electric: false,
};

println!("— Driving the Car —");
drive(&my_car);

println!("n— Riding the Bike —");
drive(&my_bike);
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// Defines an error type for our operation failures.
#[derive(Debug)]
enum Error {
    OutOfFuel,
}

// The Vehicle trait represents a common behavior contract.
// Any type implementing Vehicle must know how to start, stop, and honk.
trait Vehicle {
    // Instance method: Start the vehicle.
    fn start(&self) -> Result<(), Error>;

    // Instance method: Stop the vehicle.
    fn stop(&self);

    // Default implementation: Provide a default honk behavior.
    // Types can override this if they need special behavior.
    fn honk(&self) {
        println!("Beep beep!");
    }
}

// Concrete type representing a Car.
struct Car {
    model: String,
    fuel: u8, // Fuel percentage (0 to 100)
}

// Another concrete type representing a Bike.
struct Bike {
    brand: String,
    electric: bool,
}

// Implement Vehicle for Car.
impl Vehicle for Car {
    // Start the car if it has fuel.
    fn start(&self) -> Result<(), Error> {
        if self.fuel > 0 {
            println!("{} is starting...", self.model);
            Ok(())
        } else {
            println!("{} cannot start! Out of fuel.", self.model);
            Err(Error::OutOfFuel)
        }
    }

    // Stop the car.
    fn stop(&self) {
        println!("{} is stopping...", self.model);
    }

    // Overriding the default honk behavior.
    fn honk(&self) {
        println!("{} says: Honk honk!", self.model);
    }
}

// Implement Vehicle for Bike.
impl Vehicle for Bike {
    fn start(&self) -> Result<(), Error> {
        if self.electric {
            println!("{} is starting silently...", self.brand);
        } else {
            println!("{} is ready to pedal!", self.brand);
        }
        Ok(())
    }

    // Stop the bike.
    fn stop(&self) {
        println!("{} is slowing down...", self.brand);
    }

    // Bikes can honk, but let's keep the default behavior.
}

// A function that works with any type that implements the Vehicle trait.
fn drive<T: Vehicle>(vehicle: &T) {
    let _ = vehicle.start();
    vehicle.honk();
    vehicle.stop();
}

fn main() {
    let my_car = Car {
        model: String::from("Tesla Model S"),
        fuel: 80,
    };

    let my_bike = Bike {
        brand: String::from("Giant"),
        electric: false,
    };

    println!("--- Driving the Car ---");
    drive(&my_car);

    println!("n--- Riding the Bike ---");
    drive(&my_bike);
}
// Defines an error type for our operation failures.
#[derive(Debug)]
enum Error {
    OutOfFuel,
}

// The Vehicle trait represents a common behavior contract.
// Any type implementing Vehicle must know how to start, stop, and honk.
trait Vehicle {
    // Instance method: Start the vehicle.
    fn start(&self) -> Result<(), Error>;

    // Instance method: Stop the vehicle.
    fn stop(&self);

    // Default implementation: Provide a default honk behavior.
    // Types can override this if they need special behavior.
    fn honk(&self) {
        println!("Beep beep!");
    }
}

// Concrete type representing a Car.
struct Car {
    model: String,
    fuel: u8, // Fuel percentage (0 to 100)
}

// Another concrete type representing a Bike.
struct Bike {
    brand: String,
    electric: bool,
}

// Implement Vehicle for Car.
impl Vehicle for Car {
    // Start the car if it has fuel.
    fn start(&self) -> Result<(), Error> {
        if self.fuel > 0 {
            println!("{} is starting...", self.model);
            Ok(())
        } else {
            println!("{} cannot start! Out of fuel.", self.model);
            Err(Error::OutOfFuel)
        }
    }

    // Stop the car.
    fn stop(&self) {
        println!("{} is stopping...", self.model);
    }

    // Overriding the default honk behavior.
    fn honk(&self) {
        println!("{} says: Honk honk!", self.model);
    }
}

// Implement Vehicle for Bike.
impl Vehicle for Bike {
    fn start(&self) -> Result<(), Error> {
        if self.electric {
            println!("{} is starting silently...", self.brand);
        } else {
            println!("{} is ready to pedal!", self.brand);
        }
        Ok(())
    }

    // Stop the bike.
    fn stop(&self) {
        println!("{} is slowing down...", self.brand);
    }

    // Bikes can honk, but let's keep the default behavior.
}

// A function that works with any type that implements the Vehicle trait.
fn drive<T: Vehicle>(vehicle: &T) {
    let _ = vehicle.start();
    vehicle.honk();
    vehicle.stop();
}

fn main() {
    let my_car = Car {
        model: String::from("Tesla Model S"),
        fuel: 80,
    };

    let my_bike = Bike {
        brand: String::from("Giant"),
        electric: false,
    };

    println!("--- Driving the Car ---");
    drive(&my_car);

    println!("n--- Riding the Bike ---");
    drive(&my_bike);
}

What does this do?

  • Shared Interfaces & Behavioral Contracts:
    The Vehicle trait acts as a contract. Any type that implements it must provide a way to start and stop, ensuring consistency across types like Car and Bike.
  • Zero-Cost Abstractions:
    Traits in Rust allow the compiler to optimize away abstraction overhead. With monomorphization, when you call start() on a Car, Rust generates specialized code for that type without extra runtime cost.
  • Associated Functions vs. Methods:
    Notice that start() returns a Result<(), Error>. This ensures that failures (like an empty fuel tank) are handled explicitly rather than being silently ignored.
  • Default Implementations:
    The honk() method provides a default value. Implementing types can override this if they require different behavior, but they aren’t forced to if the default is sufficient.
  • Type-Specific Logic & Error Handling:
    The Car implementation checks for fuel levels before starting, while the Bike simply starts or requires pedaling. The use of Rust’s Result type ensures that any issues (like running out of fuel) are handled explicitly at compile time.

1.2 Trait Implementation Strategies

1.2.1 Concrete Type Implementations

Let’s say there are multiple vehicle types, like Car and Bike, that represent different modes of transport. You can implement Vehicle specifically for each type:

Result {
if self.fuel > 0 {
println!("{} is starting…", self.model);
Ok(())
} else {
println!("{} cannot start! Out of fuel.", self.model);
Err(Error::OutOfFuel)
}
}

fn stop(&self) {
println!("{} is stopping…", self.model);
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

struct Car {
    model: String,
    fuel: u8,
}

struct Bike {
    brand: String,
    electric: bool,
}

impl Vehicle for Car {
    fn start(&self) -> Result<(), Error> {
        if self.fuel > 0 {
            println!("{} is starting...", self.model);
            Ok(())
        } else {
            println!("{} cannot start! Out of fuel.", self.model);
            Err(Error::OutOfFuel)
        }
    }

    fn stop(&self) {
        println!("{} is stopping...", self.model);
    }
}
struct Car {
    model: String,
    fuel: u8,
}

struct Bike {
    brand: String,
    electric: bool,
}

impl Vehicle for Car {
    fn start(&self) -> Result<(), Error> {
        if self.fuel > 0 {
            println!("{} is starting...", self.model);
            Ok(())
        } else {
            println!("{} cannot start! Out of fuel.", self.model);
            Err(Error::OutOfFuel)
        }
    }

    fn stop(&self) {
        println!("{} is stopping...", self.model);
    }
}

Questions?

  • Type-Specific Logic:
    Each implementation is designed to the specific needs of the type. A Car needs fuel, while a Bike does not.
  • Error Handling:
    By using Rust’s Result type, we ensure that any issues (like running out of fuel) are handled gracefully.

1.2.2 Blanket Implementations

In Rust we are allowed to implement a trait for any data type that meets a certain condition. This is known as a blanket implementation (its like a blank cheque ). For example:

<button data-code="impl Vehicle for T {
fn start(&self) -> Result {
println!("{} is starting…", self.to_string());
Ok(())
}

fn stop(&self) {
println!("{} is stopping…", self.to_string());
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

impl<T: ToString> Vehicle for T {
    fn start(&self) -> Result<(), Error> {
        println!("{} is starting...", self.to_string());
        Ok(())
    }

    fn stop(&self) {
        println!("{} is stopping...", self.to_string());
    }
}
impl<T: ToString> Vehicle for T {
    fn start(&self) -> Result<(), Error> {
        println!("{} is starting...", self.to_string());
        Ok(())
    }

    fn stop(&self) {
        println!("{} is stopping...", self.to_string());
    }
}
  • Conditional Implementation:
    This allows us to declare that any type implementing ToString can automatically be a Vehicle. If it can be represented as a string, it can be “started” and “stopped”.
  • Trait Bound Propagation:
    The bound T: ToString ensures that the .to_string() method is available, linking the ToString trait with Vehicle.

By using traits effectively, Rust allows for powerful and flexible design while maintaining high performance and safety.

Section 2: Generics — Parametric Polymorphism

Generics let you write code that works for multiple data types without sacrificing performance. They enable you to create flexible data structures and functions that are as efficient as their specialized counterparts.

2.1 Generic Data Structures

Lets say, you need a multidimensional array like structure with compile-time enforced dimensions.

First, understanding the problem. Multidimensional arrays in programming are used, in areas like scientific computing, game development, machine learning or any domain dealing with matrices or grids. The key here is “compile-time enforced dimensions” which means the size of the array is known when you compile the code, not at runtime. This prevents errors like accessing an out-of-bounds index because the compiler checks it beforehand.

The need for a compile-time enforced multidimensional array arises when you want to ensure type safety, catch errors early, and optimize performance by leveraging Rust’s type system.

Here’s how you can use generics and const generics to achieve that:

<button data-code="// A 3D matrix with dimensions enforced at compile time
struct Matrix3D {
data: Vec, // Flattened 1D storage
}

impl Matrix3D {
// Create a new matrix filled with a default value
pub fn new(default_value: T) -> Self
where
T: Clone,
{
Self {
data: vec![default_value; X * Y * Z],
}
}

// Access an element (runtime bounds checking)
pub fn get(&self, x: usize, y: usize, z: usize) -> &T {
assert!(x < X && y < Y && z < Z, "Index out of bounds");
&self.data[x * Y * Z + y * Z + z]
}

// Mutate an element (runtime bounds checking)
pub fn set(&mut self, x: usize, y: usize, z: usize, value: T) {
assert!(x < X && y < Y && z < Z, "Index out of bounds");
self.data[x * Y * Z + y * Z + z] = value;
}
}

fn main() {
// Create a 2x3x4 matrix of zeros
let mut matrix = Matrix3D::::new(0);

// Set and get values
matrix.set(1, 2, 3, 42); // Valid
println!("{}", matrix.get(1, 2, 3)); // 42

// matrix.set(2, 0, 0, 100); // Panics at runtime: "Index out of bounds"
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

// A 3D matrix with dimensions enforced at compile time
struct Matrix3D<const X: usize, const Y: usize, const Z: usize, T> {
    data: Vec<T>, // Flattened 1D storage
}

impl<const X: usize, const Y: usize, const Z: usize, T> Matrix3D<X, Y, Z, T> {
    // Create a new matrix filled with a default value
    pub fn new(default_value: T) -> Self
    where
        T: Clone,
    {
        Self {
            data: vec![default_value; X * Y * Z],
        }
    }

    // Access an element (runtime bounds checking)
    pub fn get(&self, x: usize, y: usize, z: usize) -> &T {
        assert!(x < X && y < Y && z < Z, "Index out of bounds");
        &self.data[x * Y * Z + y * Z + z]
    }

    // Mutate an element (runtime bounds checking)
    pub fn set(&mut self, x: usize, y: usize, z: usize, value: T) {
        assert!(x < X && y < Y && z < Z, "Index out of bounds");
        self.data[x * Y * Z + y * Z + z] = value;
    }
}

fn main() {
    // Create a 2x3x4 matrix of zeros
    let mut matrix = Matrix3D::<2, 3, 4, i32>::new(0);

    // Set and get values
    matrix.set(1, 2, 3, 42); // Valid
    println!("{}", matrix.get(1, 2, 3)); // 42

    // matrix.set(2, 0, 0, 100); // Panics at runtime: "Index out of bounds"
}
// A 3D matrix with dimensions enforced at compile time
struct Matrix3D<const X: usize, const Y: usize, const Z: usize, T> {
    data: Vec<T>, // Flattened 1D storage
}

impl<const X: usize, const Y: usize, const Z: usize, T> Matrix3D<X, Y, Z, T> {
    // Create a new matrix filled with a default value
    pub fn new(default_value: T) -> Self
    where
        T: Clone,
    {
        Self {
            data: vec![default_value; X * Y * Z],
        }
    }

    // Access an element (runtime bounds checking)
    pub fn get(&self, x: usize, y: usize, z: usize) -> &T {
        assert!(x < X && y < Y && z < Z, "Index out of bounds");
        &self.data[x * Y * Z + y * Z + z]
    }

    // Mutate an element (runtime bounds checking)
    pub fn set(&mut self, x: usize, y: usize, z: usize, value: T) {
        assert!(x < X && y < Y && z < Z, "Index out of bounds");
        self.data[x * Y * Z + y * Z + z] = value;
    }
}

fn main() {
    // Create a 2x3x4 matrix of zeros
    let mut matrix = Matrix3D::<2, 3, 4, i32>::new(0);

    // Set and get values
    matrix.set(1, 2, 3, 42); // Valid
    println!("{}", matrix.get(1, 2, 3)); // 42

    // matrix.set(2, 0, 0, 100); // Panics at runtime: "Index out of bounds"
}
  • Const Generics (X, Y, Z): Enforce dimensions at compile time.
  • Flattened 1D Storage: Uses a Vec<T> for simplicity, but dimensions are checked on access.
  • Runtime Bounds Checks: Prevent invalid memory access (trade-off for safety).

2.2 Advanced Function Generics

When working with complex algorithms like topological sorting, you might need to work with various types representing nodes, edges, and graphs. Here’s an example that uses multiple type parameters along with trait bounds:

<button data-code="fn topological_sort(graph: G) -> Result<Vec, CycleError>
where
G: Graph + Traversable,
N: Hash + Eq,
E: Directed,
{
// Implementation of Kahn's algorithm would go here
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn topological_sort<N, E, G>(graph: G) -> Result<Vec<N>, CycleError>
where
    G: Graph<Node = N, Edge = E> + Traversable,
    N: Hash + Eq,
    E: Directed,
{
    // Implementation of Kahn's algorithm would go here
}
fn topological_sort<N, E, G>(graph: G) -> Result<Vec<N>, CycleError>
where
    G: Graph<Node = N, Edge = E> + Traversable,
    N: Hash + Eq,
    E: Directed,
{
    // Implementation of Kahn's algorithm would go here
}
  • Multiple Type Parameters: Separate parameters for node (N), edge (E), and graph (G) allow you to abstract over the various components of a graph.
  • Trait Constraints: The function requires that the graph supports certain behaviors (like traversal and having associated node and edge types), ensuring that the algorithm can rely on specific operations.
  • Associated Types: Traits like Graph can define types within them (such as Node and Edge), helping maintain a clear and consistent API.

Section 3: Trait-Generic Synergy

The real fun begins when you combine traits and generics. This synergy lets us write code that is both flexible and efficient.

3.1 Polymorphic Dispatch

Static dispatch happens when Rust uses monomorphization to generate type-specific code at compile time. Consider the following function:

<button data-code="fn process_data(item: &T) -> Vec {
println!("Processing {:?}", item);
item.serialize()
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn process_data<T: Serializer + Debug>(item: &T) -> Vec<u8> {
    println!("Processing {:?}", item);
    item.serialize()
}
fn process_data<T: Serializer + Debug>(item: &T) -> Vec<u8> {
    println!("Processing {:?}", item);
    item.serialize()
}
  • Static Dispatch: The compiler generates a unique version of process_data for every concrete type T, ensuring no runtime overhead.
  • Trait Composition: Combining Serializer and Debug as bounds lets you ensure that any type passed to this function can both serialize itself and be formatted for debugging.

3.2 Dynamic Trait Objects

Sometimes one need flexibility at runtime when you work with heterogeneous types. Rust provides trait objects for this purpose:

<button data-code="fn log_serializers(items: &mut [Box]) {
for item in items {
let data = item.serialize();
// Universal logging logic
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn log_serializers(items: &mut [Box<dyn Serializer>]) {
    for item in items {
        let data = item.serialize();
        // Universal logging logic
    }
}
fn log_serializers(items: &mut [Box<dyn Serializer>]) {
    for item in items {
        let data = item.serialize();
        // Universal logging logic
    }
}
  • Runtime Polymorphism: Trait objects (dyn Serializer) allow you to work with types that implement Serializer without knowing their concrete types at compile time.
  • Object Safety: Only traits that meet certain criteria (for example, not containing methods that return Self) can be turned into trait objects.

Section 4: Advanced Trait Patterns

Rust’s trait system supports advanced patterns that help organize complex codebases.

4.1 Associated Types vs Generic Parameters

Rust offers two ways to abstract over types within traits: associated types and generic parameters.

Option;
}
trait Converter {
fn convert(&self) -> T;
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
}
trait Converter<T> {
    fn convert(&self) -> T;
}
trait Iterator {
    type Item;

    fn next(&mut self) -> Option<Self::Item>;
}
trait Converter<T> {
    fn convert(&self) -> T;
}

Comparison:

  • Associated Types:
    Each implementation of the Iterator trait has one definitive Item type. This simplifies the interface because it doesn’t require extra generic parameters when using the trait.
  • Generic Parameters:
    In contrast, using a generic parameter (like in Converter<T>) allows a single type to potentially have multiple conversion behaviors. This is useful when a type needs to be flexible in different contexts.

4.2 Supertrait Composition

Traits can require other traits, thereby composing behavior in a hierarchical fashion.

Schema {
Schema::new()
.with_type("object")
.with_properties()
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait JsonSchema: Serializer + Debug {
    fn schema() -> Schema {
        Schema::new()
            .with_type("object")
            .with_properties()
    }
}
trait JsonSchema: Serializer + Debug {
    fn schema() -> Schema {
        Schema::new()
            .with_type("object")
            .with_properties()
    }
}
  • Trait Inheritance:
    By declaring JsonSchema: Serializer + Debug, any type implementing JsonSchema must also implement both Serializer and Debug. This enforces a set of behaviors.
  • Default Behavior:
    The schema method provides a default implementation, which can be overridden if a more specialized behavior is needed.

Section 5: Performance Characteristics

Understanding the performance implications of generics and traits can help you write high performance Rust code.

5.1 Monomorphization Analysis

Rust uses monomorphization to generate optimized code for each concrete type used in generic functions. Consider this example:

<button data-code="fn add<T: Add>(a: T, b: T) -> T {
a + b
}

// Compiler generates:
fn add_i32(a: i32, b: i32) -> i32 { a + b }
fn add_f64(a: f64, b: f64) -> f64 { a + b }” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

fn add<T: Add<Output = T>>(a: T, b: T) -> T {
    a + b
}

// Compiler generates:
fn add_i32(a: i32, b: i32) -> i32 { a + b }
fn add_f64(a: f64, b: f64) -> f64 { a + b }
fn add<T: Add<Output = T>>(a: T, b: T) -> T {
    a + b
}

// Compiler generates:
fn add_i32(a: i32, b: i32) -> i32 { a + b }
fn add_f64(a: f64, b: f64) -> f64 { a + b }
  • Zero-Cost Abstraction: There is no runtime overhead compared to writing separate functions for each type.
  • Code Bloat Mitigation: When performance is critical, you can choose dynamic dispatch in selective places to keep binary sizes manageable.

5.2 Trait Object Costs

Using dynamic trait objects introduces some overhead. For example:

<button data-code="let objects: Vec = vec![&square, &circle];” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-1/2 -translate-y-1/2 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

let objects: Vec<&dyn Draw> = vec![&square, &circle];
let objects: Vec<&dyn Draw> = vec![&square, &circle];
  • **Vtable Overhead: (**virtual table Overhead ) Each trait object carries an extra pointer (a vtable) to facilitate dynamic dispatch, typically doubling the pointer size (data pointer + vtable pointer).
  • Tradeoffs: While dynamic dispatch offers flexibility, it may incur a slight runtime cost (~5% in some cases) compared to monomorphized code, though it often results in smaller binary sizes.

Section 6: Real-World Applications

The power of traits and generics becomes evident in practical applications ranging from cross-platform development to embedded systems.

6.1 Cross Platform Serialization

When targeting multiple platforms, you can define a trait that adapts serialization logic to platform-specific requirements:

Vec;
fn serialize_for_ios(&self) -> NSData;
}

impl PlatformSerializer for T {
fn serialize_for_android(&self) -> Vec {
self.serialize()
}

fn serialize_for_ios(&self) -> NSData {
// Conversion logic to iOS data type
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait PlatformSerializer {
    fn serialize_for_android(&self) -> Vec<u8>;
    fn serialize_for_ios(&self) -> NSData;
}

impl<T: Serializer> PlatformSerializer for T {
    fn serialize_for_android(&self) -> Vec<u8> {
        self.serialize()
    }

    fn serialize_for_ios(&self) -> NSData {
        // Conversion logic to iOS data type
    }
}
trait PlatformSerializer {
    fn serialize_for_android(&self) -> Vec<u8>;
    fn serialize_for_ios(&self) -> NSData;
}

impl<T: Serializer> PlatformSerializer for T {
    fn serialize_for_android(&self) -> Vec<u8> {
        self.serialize()
    }

    fn serialize_for_ios(&self) -> NSData {
        // Conversion logic to iOS data type
    }
}
  • Trait Specialization:
    You can build platform-specific behavior on top of the general Serializer trait.
  • Code Reuse:
    Core serialization logic is shared, while adaptations for different platforms are encapsulated within the trait’s implementations.

6.2 Embedded Systems Pattern

In resource-constrained environments like embedded systems, traits offer a uniform way to interact with hardware components.

Result;
}

struct TemperatureSensor {
address: u8,
i2c: I2cBus,
}
impl Sensor for TemperatureSensor {
fn read(&mut self) -> Result {
let raw = self.i2c.read(self.address)?;
Ok(raw as f32 / 100.0)
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>

trait Sensor {
    fn read(&mut self) -> Result<f32, SensorError>;
}

struct TemperatureSensor {
    address: u8,
    i2c: I2cBus,
}
impl Sensor for TemperatureSensor {
    fn read(&mut self) -> Result<f32, SensorError> {
        let raw = self.i2c.read(self.address)?;
        Ok(raw as f32 / 100.0)
    }
}
trait Sensor {
    fn read(&mut self) -> Result<f32, SensorError>;
}

struct TemperatureSensor {
    address: u8,
    i2c: I2cBus,
}
impl Sensor for TemperatureSensor {
    fn read(&mut self) -> Result<f32, SensorError> {
        let raw = self.i2c.read(self.address)?;
        Ok(raw as f32 / 100.0)
    }
}
  • Hardware Abstraction:
    The Sensor trait defines a common interface, letting you write generic code that can work with any sensor type.
  • Error Propagation:
    Rust’s ? operator simplifies error handling, making the code both robust and easy to maintain.

Conclusion

Rust’s traits and generics provide a uniquely powerful combination of abstraction and control. Here are some key takeaways:

  • Trait Design:
    Use associated types for single-concern interfaces and generic parameters when multiple conversion paths or behaviors are needed.
  • Generic Strategies:
    Leverage monomorphization to maintain performance in critical sections of your code, and apply dynamic dispatch where flexibility is essential.
  • Composition Patterns:
    Build complex systems by combining traits via inheritance (supertraits) and blanket implementations. This encourages code reuse while keeping your codebase modular and maintainable.

In our next section, we’ll explore how Rust’s type system and ownership model contribute to robust error handling. From Result and Option to custom error types and best practices. The journey from Rust rookie to pro continues with increasingly sophisticated applications of these foundational concepts.

Follow this series and join us in mastering Rust from scratch!
Reach out here on Linkedin