What I'm attempting to do is creating generic function that compares two instances of something that has length.
My code:
fn main() {
let vec1 = vec!(1, 2, 3);
let vec2 = vec!(1, 2, 3, 4);
println!("Longest vector is: {:?}", longer_vec_gen(&vec1, &vec2));
println!("Longest iterator is {:?}", longer_exact_size_iterator(&vec1.iter(), &vec2.iter()))
}
fn longer_vec_gen<'a, T>(x: &'a Vec<T>, y: &'a Vec<T>) -> &'a Vec<T> {
if x.len() > y.len() {
x
} else {
y
}
}
fn longer_exact_size_iterator<'a, T: ExactSizeIterator>(x: &'a T, y: &'a T) -> &'a T {
if x.len() > y.len() {
x
} else {
y
}
}
Both of those functions works however the first one works only for Vec so I wanted to make step forward and do it for anything that has length. The second one kinda achieves this, but right now I'm forced to use .iter() on parameters while calling this function which I would love to avoid.
Another problem is that i can't pass String or string literals to this function.
What I would love to achieve is creating function longer that would take any two elements that has implemented function .len() so this code would run without errors:
fn main() {
let vec1 = vec!(1, 2, 3);
let vec2 = vec!(1, 2, 3, 4);
println!("Longer vector is: {:?}", longer(&vec1, &vec2));
let string1 = String::from("abcd");
let string2 = String::from("xyz");
println!("Longest string is : {:?}", longer(&string1, &string2))
}
fn longer(...) {
...
}