Generic Programming

🦀 Rust Lesson 13 Advanced

Generics allow you to write functions and structs that work with multiple data types, preventing code duplication while preserving strict type safety.

1 Generics Declarations & Trait Bounds

Generics use placeholder type variables: `fn swap<T>(x: T) {}`. When using generics, you can restrict placeholders to only accept types that implement specific traits (known as **Trait Bounds**), allowing you to call trait methods on generic objects safely: `<T: Display>`.

2 Generics Code

Let's run a program illustrating generic structures and trait bounds constraints:

Rust — Generics ▶ Run Code
use std::fmt::Display; // Needed for Display trait bound

// Generic struct representing a Coordinate point
struct Point {
    x: T,
    y: T,
}

// Generic function with Display trait bound restricting placeholder types
fn print_coordinate(label: &str, val: T) {
    println!("{}: {}", label, val);
}

fn main() {
    let int_point = Point { x: 5, y: 10 };
    let float_point = Point { x: 1.5, y: 3.5 };

    println!("Int point x: {}", int_point.x);
    println!("Float point x: {}", float_point.x);

    print_coordinate("Integer", 42);
    print_coordinate("String Slice", "Coordinates resolved");
}
3 Code Challenge
Challenge: Write a generic function called `largest` that accepts a slice of items and returns the largest element. Use trait bounds (`PartialOrd`) to ensure the types can be compared.