capypad
0 day streak
rust / beginner
Snippet

Generic Functions

Generic functions work with multiple types using type parameters. The <T: PartialOrd> syntax specifies that T must be a type that can be compared with the > operator. This allows the same function to work with integers, chars, and any other comparable type.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn largest<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list {
if item > largest {
largest = item;
}
}
largest
}
 
fn main() {
let numbers = vec![34, 50, 25, 100, 65];
println!("The largest number is {}", largest(&numbers));
let chars = vec!['y', 'm', 'a', 'q'];
println!("The largest char is {}", largest(&chars));
}
Breakdown
1
fn largest<T: PartialOrd>(
Function with generic type T constrained by PartialOrd trait
2
list: &[T]
Parameter is a slice of type T
3
let mut largest = &list[0];
Mutable reference initialized to first element
4
if item > largest {
Comparison requires PartialOrd trait bound
5
largest = item;
Updates reference to larger value found