Sub topic 2
Generic functions
This chapter assumes you can write basic Rust functions, take slices and references as arguments, and know what a trait is. Bounds and monomorphization get their own chapters, so they appear here only in outline.
The duplication problem
Suppose you need the largest element of a slice of i32 and of a slice of f64. The bodies are identical. Only the types differ. A generic function lets you write the body once and leave the type as a placeholder.
Declaring a type parameter
A type parameter is a name for a type that the caller chooses. You declare it in angle brackets after the function name, and you can then use it in the signature and the body.
fn largest<T: PartialOrd>(items: &[T]) -> &T {
let mut largest = &items[0];
for item in items {
if item > largest {
largest = item;
}
}
largest
}
fn main() {
println!("{}", largest(&[3, 9, 2]));
println!("{}", largest(&[1.5, 0.2]));
println!("{}", largest(&['a', 'z', 'q']));
}The pieces of the signature are:
<T: PartialOrd>declaresTand says it must implementPartialOrd.&[T]is a slice of any element type.-> &Treturns a reference to one element, so nothing is copied or moved.
By convention, type parameters have short, capitalized names such as T, U, or K and V.
Why the bound is required
The compiler checks a generic function once, against what it knows about T. It knows nothing about T except the bounds you give it. Without : PartialOrd, the expression item > largest is rejected with an error like "binary operation > cannot be applied to type &T". Rust does not wait to see which concrete types you pass. If the body uses an operation, the signature has to promise it.
flowchart TDInference and the turbofish
In the example above you never wrote largest::<i32>. The compiler inferred T from the argument. When inference has nothing to work from, or you want to be explicit, supply the type with the turbofish syntax, ::<Type>, placed after the function name.
You have probably used it already in "42".parse::<i32>(). The same syntax works on your own functions.
Handling the empty slice
largest panics on an empty slice because items[0] is out of range. A generic function can return Option just as a normal one can, and that is usually the better design.
fn largest_opt<T: PartialOrd>(items: &[T]) -> Option<&T> {
let mut iter = items.iter();
let mut largest = iter.next()?;
for item in iter {
if item > largest {
largest = item;
}
}
Some(largest)
}
fn main() {
let empty: [i32; 0] = [];
println!("{:?}", largest_opt(&empty));
println!("{:?}", largest_opt::<f64>(&[1.5, 0.2]));
}This prints None and then Some(1.5). The ? operator returns None early when the iterator has no first element.
Common errors
- Missing bound. Using
>,+,{}formatting, or.clone()on a bareTfails to compile. Add the matching trait bound. - Moving out of a slice. Returning
Tinstead of&Tfrom&[T]fails with "cannot move out of index". Return a reference, or add aCopyorClonebound. - Ambiguous type.
let x = Default::default();fails because nothing says which type you want. Annotate the variable or use the turbofish. - Two parameters, one type.
fn pair<T>(a: T, b: T)requires both arguments to have the same type. Passing ani32and anf64is an error. Declare<T, U>if they may differ.
Exercise
Write the signature of a generic function smallest that takes a slice of any comparable type and returns a reference to the smallest element, or None if the slice is empty.
Show answer
fn smallest<T: PartialOrd>(items: &[T]) -> Option<&T>. The bound PartialOrd is needed to compare elements, and the Option return type handles the empty slice without panicking.