Chen Ease
Chen Ease

Reputation: 11

Rust book Listing 10-15:when i use 'let largest = item', the 'largest' can't be changed

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

Upvotes: 0

Views: 153

Answers (2)

piertoni
piertoni

Reputation: 2021

You are defining again the variable largest inside another scope, so in fact you are shadowing it. When the code exits the curly brackets {} than the internal largest disappears. As the compiler said, the inner largest is in fact not used and the warning is correct.

Scope and Shadowing

Upvotes: 1

mousetail
mousetail

Reputation: 8010

The second let largest creates a new block-scoped variable also named largest but unrelated to the outer largest. It is destroyed at the end of the loop cycle.

To fix your code remove the second let so that you have only one variable named largest and make the outer largest mutable so you can assign to it.

In fact, the only way this code works if you use the exact code form the book.

Upvotes: 1

Related Questions