Generic types incomprehensible code in the documentation

Hello everyone. I'm currently exploring generic types from the documentation. I have a question regarding the code. I wrote two functions, after the loop you can see the largest. Why write this, what does it do?

fn largest_i32(list: &[i32]) -> i32 {
    let mut largest = list[0];

    for &item in list {
        if item > largest {
            largest = item;
        }
    }

    largest // why is it?
}

fn largest_char(list: &[char]) -> char {
    let mut largest = list[0];

    for &item in list {
        if item > largest {
            largest = item;
        }
    }

    largest // why is it?
}

That’s returning the calculated value from the function: Code blocks, including function bodies, evaluate to the last expression in the block.

Thanks! Does the largest contain the function result and return it?

Yes, that's correct:

fn largest_char(list: &[char]) -> char {
    // Define variable `largest`; store a copy of item 0.
    let mut largest = list[0];

    // For every item,
    for &item in list {
        // If it is bigger than the best we've found so far,
        if item > largest {
            // Store it in the variable `largest`.
            largest = item;
        }
    }

    // Now, return the most-recently stored item.
    largest
}
1 Like

Thank you very much! Much better now