0

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?

9
  • I'm not particularly experienced with Rust but aren't lifetime parameters supposed to be used here? Commented May 3, 2022 at 14:37
  • Try let mut biggest = &vec[0]; You want biggest to be a reference instead of a copy of vec[0]. Commented May 3, 2022 at 14:38
  • @Bernard that brings the issue of comparing item with biggest. Commented May 3, 2022 at 14:39
  • 1
    You shouldn't need a lifetime annotation - if there is only one reference parameter, Rust deduces that the returned reference must have the same lifetime as the reference parameter. Lifetime deduction only looks at the function signature, not the body. Commented May 3, 2022 at 14:43
  • 1
    The problem here is that if you want to return a reference, biggest would have to hold a reference the entire time. Commented May 3, 2022 at 14:47

1 Answer 1

5

This is probably what you want:

fn largest<T : PartialOrd>(vec : &[T]) -> &T{

let mut biggest = &vec[0];
 
for item in vec{
    if item > biggest{
        biggest = item
    }
 }

 biggest
}

biggest is a reference of type mut &T, so the reference can be rebinded later at the line biggest = item.

By doing it this way, at no point in the code will you be making copies of T, and so will be returning a reference to one of the elements of the slice.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.