Function that returns the reference to a value in a list ( to find maximum element )

Listing 10-15 in the Book gives the following example to find the maximum value in a list:

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T {
    let mut largest = list[0];

    for &item in list.iter() {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest(&number_list);
    println!("The largest number is {}", result);

    let char_list = vec!['y', 'm', 'a', 'q'];

    let result = largest(&char_list);
    println!("The largest char is {}", result);
}

And then gives an exercise to solve it by returning &T:

Another way we could implement largest is for the function to return a reference to a T value in the slice. If we change the return type to &T instead of T , thereby changing the body of the function to return a reference, we wouldn’t need the Clone or Copy trait bounds and we could avoid heap allocations. Try implementing these alternate solutions on your own!

I'm unable to do that. How can I do this?

1 Like

It's more or less the same.

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];

    for item in list.iter() {
        if item > largest {
            largest = &item;
        }
    }

    largest
}

You remove the requirement for Copy. You set it to return &T, and you store a reference in largest.

2 Likes

Thank you @alice for the help!
The version I tried was this:

fn largest<T: PartialOrd>(list: &[T]) -> &T {
    let mut largest = &list[0];
    for &item in list.iter() {
        if &item > largest {
            largest = &item;
        }
    }
    return largest;
}

Why can I not use for &item in list.iter() {? I get the following error, which I do not understand:

error[E0507]: cannot move out of a shared reference
 --> src/main.rs:3:18
  |
3 |     for &item in list.iter() {
  |         -----    ^^^^^^^^^^^
  |         ||
  |         |data moved here
  |         |move occurs because `item` has type `T`, which does not implement the `Copy` trait
  |         help: consider removing the `&`: `item`
1 Like

This is because the for _ in spot is a pattern, so by typing &value, you're saying that "If I have an &thing, then I want the thing". But that requires a copy out of the reference.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.