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

This example demonstrates how to use generic function in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

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

More Generics Examples