rust 泛型02
定义一个求数组种最大值的泛型函数fn<T>largest(list: &[T]),
largest1: 瑕疵在传入的参数于只适用于实现了Copy特征的类型.
largest2: 添加Clone约束,改进后没有了参数类型的限制,但Clone会有额外的性能开销,会在堆上重新分配内存。
largest3:修改后返回引用类型,避免了参数只能使用实现了Copy特征类型的问题,且不会额外分配内存。
fn largest1<T: PartialOrd + Copy>(list: &[T]) -> T { let mut largest = list[0]; for &item in list.iter() { if item > largest { largest = item; } } largest }
fn largest2<T: PartialOrd + Copy + Clone>(list: &[T]) -> T {
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn largest3<T: PartialOrd>(list: &[T]) -> &T { let mut largest = &list[0]; for item in list.iter() { if item > largest { largest = item; } } largest } fn main() { let number_list = vec![34, 50, 25, 100, 65]; let result = largest3(&number_list); println!("The largest number is {}", result); let char_list = vec!['y', 'm', 'a', 'q']; let result = largest3(&char_list); println!("The largest char is {}", result); }
output:
The largest number is 100
The largest char is y
作者:天使不设防
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.