Day 15: Generics
MediumGenericsType ParametersReusability

Day 15: Generics

Generics let you write code that works with multiple types while maintaining type safety.

Generic Functions

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}

Generic Structs

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

let integer_point = Point { x: 5, y: 10 };
let float_point = Point { x: 1.0, y: 4.0 };

Multiple Generic Types

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

let mixed = Point { x: 5, y: 4.0 };

Generics have zero runtime cost in Rust! The compiler generates specialized code for each concrete type (monomorphization).

Trait Bounds

Constrain what types can be used:

fn print_debug<T: std::fmt::Debug>(item: T) {
    println!("{:?}", item);
}

// Multiple bounds
fn compare<T: PartialOrd + Copy>(a: T, b: T) -> T {
    if a > b { a } else { b }
}

The Task

Implement a generic largest<T> function that finds the largest element in a slice.

Requirements

  • Works with any type that implements PartialOrd + Copy
  • Returns the value (not a reference, since we have Copy)
  • largest(&[34, 50, 25, 100, 65])100

Hints

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];
    for &item in list {
        if item > largest {
            largest = item;
        }
    }
    largest
}
Language: Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
Output
Run to see the result here.
    Day 15: Generics · RUST Challenge | learn.sol