I'm learning Rust by the rust book.But when I try the Listing 10-15, I found I can't change the value of 'largest' by using 'let'. The introduction of the topic is
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!
My code is:
fn largest<T>(list: &[T]) -> &T
where T: PartialOrd + Copy
{
let largest = &list[0];
for item in list.iter() {
if item > largest {
let largest = item;
}
}
return largest
}
fn main() {
let number_list = vec![34.0, 50.2, 25.32, 100.32, 65.32, 100.33];
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);
}
I get 1 warning:
warning: unused variable: `largest`
--> src/main.rs:8:17
|
8 | let largest = item;
| ^^^^^^^ help: if this is intentional, prefix it with an underscore: `_largest`
|
= note: `#[warn(unused_variables)]` on by default
warning: 1 warning emitted
And the result is not right:
The largest number is 34
The largest char is y