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!
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`
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.