Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ifyouseewendy/d1fb03df4614394573bef0480812a62f to your computer and use it in GitHub Desktop.
Save ifyouseewendy/d1fb03df4614394573bef0480812a62f to your computer and use it in GitHub Desktop.
Use **Trait Bound** to implement a generic find largest function. Referenced from https://doc.rust-lang.org/book/ch10-02-traits.html
fn find_largest_1<T: PartialOrd + Copy>(list: &[T]) -> T {
let mut largest = list[0];
for number in list {
if *number > largest {
largest = *number;
}
}
largest
}
fn find_largest_2<T: PartialOrd + Clone>(list: &[T]) -> T {
let mut largest = list[0].clone();
for number in list {
if *number > largest {
largest = number.clone();
}
}
largest
}
fn find_largest_3<T: PartialOrd>(list: &[T]) -> &T {
let mut largest = &list[0];
for item in list.iter() {
if *item > *largest {
largest = item;
}
}
largest
}
fn main() {
let list = vec![34, 50, 25, 100, 65];
println!("The largest one is {}", find_largest_1(&list));
let list = vec!["a", "ab", "abc"];
println!("The largest one is {}", find_largest_2(&list));
let list = vec!["a", "ab", "abc"];
println!("The largest one is {}", find_largest_3(&list));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment