I have the following two implementations of extracting the largest item out of a collection, one implementation is for a LinkedList
and one for a Vec
.
Live Demo:
use std::collections::LinkedList;
fn get_largest_in_list(coll: &LinkedList<i32>) -> i32 {
let mut largest: i32 = 0;
for &item in coll {
if item > largest {
largest = item;
}
}
largest
}
macro_rules! linked_list {
($($e:expr),*) => {{
let mut list = LinkedList::new();
$(list.push_back($e);)*
list
}};
}
fn get_largest_in_vec(coll: &Vec<i32>) -> i32 {
let mut largest: i32 = 0;
for &item in coll {
if item > largest {
largest = item;
}
}
largest
}
pub fn main() {
// let mut s = String::from("hello world");
// let len = s.len();
let myvec: Vec<i32> = vec![9, 4, 2, 13, 81, 92];
let largest: i32 = get_largest_in_vec(&myvec);
println!("The largest item in vector is {:?}", largest);
let mylist: LinkedList<i32> = linked_list![10, 15, 2, 3, 7, 100];
let largest: i32 = get_largest_in_list(&mylist);
println!("The largest item in list is {:?}", largest);
// println!("{:?}", myvec);
}
You can see that there is quite some amount of code duplication. What I want to do now is to write a generic function get_largest that works for both LinkedList
and Vec
. What would be the rustacean way to do this?
(side question: It appears there is no linked_list! macro in the standard library, so I had to write my own.. Why is that?)