fn find_max<T: Clone + PartialOrd>(collection: &[T]) -> Option<T> {
if collection.is_empty() {
None
} else {
let mut max = collection[0].clone();
for item in collection.iter().skip(1) {
if item > &max {
max = item.clone();
}
}
Some(max)
}
}
使用这些trait bounds的原因
Clone
trait:因为函数需要返回集合中最大元素的克隆值,所以类型T
必须实现Clone
trait,这样才能克隆出最大元素并返回。
PartialOrd
trait:为了比较集合中的元素大小,类型T
需要实现PartialOrd
trait。PartialOrd
trait提供了>
、<
等比较操作符的功能,使得我们可以判断哪个元素更大。
不满足这些bounds时的编译错误
- 未实现
Clone
trait:如果类型T
没有实现Clone
trait,在clone()
调用处会出现编译错误,例如error[E0599]: no method named 'clone' found for type 'T' in the current scope
。
- 未实现
PartialOrd
trait:如果类型T
没有实现PartialOrd
trait,在比较if item > &max
处会出现编译错误,例如error[E0369]: binary operation '>' cannot be applied to type 'T'
。