RRust By Example
intermediateGenerics

Generic Function

Write functions that work with multiple types using generics.

Generic Function

Write functions that work with multiple types using generics.

Difficulty

Intermediate

Code

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

fn main() {
    let numbers = vec![34, 50, 25, 100, 65];
    println!("largest: {}", largest(&numbers));

    let chars = vec!['y', 'm', 'a', 'q'];
    println!("largest: {}", largest(&chars));
}

Explanation

Generics work with multiple types. Trait bounds constrain operations.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the generics category to build a complete understanding of this topic.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Generics Examples