Rust is the anti-Python (which is great!)

Finding the max of a generically typed vector, requires one to implement the Copy trait as below:

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

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

    largest
}

For large data structures, line ` let mut largest = list[0]; ` can be a problem as it copies list[0] to largest.

Below is an implementation that doesn’t impact the heap and the memory allocator. It should be faster too. My biggest doubt was “will let mut largest = &list[0]; change the value of the input list?” The answer is “Rust is cool. Rust is smart”, in one word “No”

use std::fmt;

fn largest<T: PartialOrd + fmt::Debug>(list: &[T]) -> &T {
    let mut largest = &list[0];
    println!("before {:?}", &list);
    
    for item in list.iter() {
        if item > largest {
            largest = &item;
            println!("before {:?}", &list);

        }
    }

    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);
}

The output of the code above is

before [34, 50, 25, 100, 65]
before [34, 50, 25, 100, 65]
before [34, 50, 25, 100, 65]
The largest number is 100
before ['y', 'm', 'a', 'q']
The largest char is y

Clearly list stays untouched.