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.rs372 chars12 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