# 泛型、trait 和生命周期

ch10-00-generics.md
commit 48b057106646758f6453f42b7887f34b8c24caf6

## 提取函数来减少重复

fn main() {
let number_list = vec![34, 50, 25, 100, 65];

let mut largest = number_list[0];

for number in number_list {
if number > largest {
largest = number;
}
}

println!("The largest number is {}", largest);
assert_eq!(largest, 100);
}


fn main() {
let number_list = vec![34, 50, 25, 100, 65];

let mut largest = number_list[0];

for number in number_list {
if number > largest {
largest = number;
}
}

println!("The largest number is {}", largest);

let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

let mut largest = number_list[0];

for number in number_list {
if number > largest {
largest = number;
}
}

println!("The largest number is {}", largest);
}


fn largest(list: &[i32]) -> i32 {
let mut largest = list[0];

for &item in list {
if item > largest {
largest = item;
}
}

largest
}

fn main() {
let number_list = vec![34, 50, 25, 100, 65];

let result = largest(&number_list);
println!("The largest number is {}", result);
assert_eq!(result, 100);

let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

let result = largest(&number_list);
println!("The largest number is {}", result);
assert_eq!(result, 6000);
}


largest 函数有一个参数 list，它代表会传递给函数的任何具体的 i32值的 slice。函数定义中的 list 代表任何 &[i32]。当调用 largest 函数时，其代码实际上运行于我们传递的特定值上。

1. 找出重复代码。
2. 将重复代码提取到了一个函数中，并在函数签名中指定了代码中的输入和返回值。
3. 将重复代码的两个实例，改为调用函数。