Generic functions and bounds in Rust
A type parameter with bounds: one function, every type that satisfies the trait.
fn biggest<T: PartialOrd + Copy>(values: &[T]) -> T {
let mut best = values[0];
for v in values {
if *v > best {
best = *v;
}
}
best
}
fn describe<T>(value: T) -> String
where
T: std::fmt::Debug + Clone,
{
format!("{:?}", value.clone())
}
fn main() {
println!("{}", biggest(&[3, 9, 2]));
println!("{}", biggest(&[1.5, 0.5]));
println!("{}", describe(vec![1, 2]));
}
How it works
<T: PartialOrd>says T must be comparable.- A
whereclause carries longer bound lists off the signature. - Monomorphisation compiles one copy per concrete type.
Keywords and builtins used here
CloneCopyPartialOrdStringTbiggestdescribefnforifinletmainmutstdwhere
The run, in numbers
- Lines
- 22
- Characters to type
- 367
- Tokens
- 145
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 83 seconds.
Step 1 of 4 in Generics, step 4 of 19 in Traits & generics.