Rust

Generic Function with Trait Bounds

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Use `T: Trait` to require a capability on a generic parameter. The `where` clause is the more readable variant when bounds get long.
Rust
Raw
use std::fmt::Display;
use std::ops::Add;

// Inline bound syntax — fine for one constraint
fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut max = list[0];
    for &x in &list[1..] {
        if x > max { max = x; }
    }
    max
}

// `where` clause — clearer when there are many bounds
fn print_sum<T, U>(a: T, b: U) -> impl Display
where
    T: Display + Add<U, Output = T>,
    U: Display + Copy,
{
    format!("{} + {} = {}", a, b, a + b)
}

fn main() {
    println!("{}", largest(&[3, 1, 4, 1, 5, 9, 2, 6]));   // 9
    println!("{}", largest(&[3.0, 1.5, 4.2, 1.1]));       // 4.2
    println!("{}", print_sum(2, 3));                       // 2 + 3 = 5
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.