Created
December 7, 2019 18:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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