Following is a program that returns the reference to the largest value of any given vector.I used generics for this, but does not work.
fn largest<T : PartialOrd>(vec : &[T]) -> &T{
let mut biggest = vec[0];
for &item in vec{
if item > biggest{
biggest = item
}
}
&biggest
}
I know I am returning a reference to a local variable, so It won't compile. The other solution is to use copy trait like,
fn largest<T : PartialOrd + Copy>(vec : &[T]) -> T{}
Is there any way so that I can return the reference and avoid using Copy trait?
let mut biggest = &vec[0];You wantbiggestto be a reference instead of a copy ofvec[0].biggestwould have to hold a reference the entire time.