find the range of a list of numbers in rust

To find the range of a list of numbers in Rust, we can use the min() and max() functions to find the minimum and maximum values in the list, and then subtract the minimum from the maximum:

main.rs
fn find_range(numbers: &[i32]) -> i32 {
    let min = numbers.iter().min().unwrap_or(&0); // If the list is empty, return 0
    let max = numbers.iter().max().unwrap_or(&0); // If the list is empty, return 0
    max - min
}

fn main() {
    let numbers = vec![5, 10, 15, 20, 25];
    let range = find_range(&numbers);
    println!("The range of the list is {}", range);
}
372 chars
12 lines

In this example, we define a function called find_range that takes a reference to a list of i32 numbers. The min() and max() functions are called on the Iterator returned by numbers.iter(), which returns the minimum and maximum values in the list, respectively. If the list is empty, we set the minimum and maximum to 0. Finally, we subtract the minimum from the maximum to compute the range.

In the main() function, we create a list of numbers and call find_range() on it. The result is printed to the console using println!(). This program should output: The range of the list is 20.

gistlibby LogSnag