Here is an example of a generic function. It takes a single parameter
T and uses it to define the type of its single argument:
fn get_length<T>(v: &[T]) -> usize {
v.len()
}
let arr = [16, -10, 120];
get_length(&arr)3The previous function does not do anything useful, and thus does not put
any constraint on the type T. Usually, we use T inside the function’s
code, like calling one of its methods or using an operator on it. This
implies that T must provide some abilities.
The following example needs the T type to be compared using the >
operator. This implies that T must implement the PartialOrd trait.
The function returns the highest element in an array of any type T:
use std::cmp::PartialOrd;
fn largest<T: PartialOrd>(arr: &[T]) -> &T {
let mut largest = &arr[0];
for item in arr {
if item > largest {
largest = item;
}
}
largest
}We apply the function first on a list of integers:
{
let number_list = vec![34, 50, 25, 100, 65];
let result = largest(&number_list);
println!("The largest number is {result}");
}The largest number is 100
()Now we apply it on a list of characters:
{
let char_list = vec!['y', 'm', 'a', 'q'];
let result = largest(&char_list);
println!("The largest char is {result}");
}The largest char is y
()