If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series.
10.1.1 Repeated Code
Let’s look at an example:
fn main (){ let number_list = vec! [ 1 , 2 , 3 , 4 , 5 ]; let mut largest = number_list [ 0 ]; for & item in number_list .iter (){ if item > largest { largest = item ; } } println! ( "The largest number is {}" , largest ); }
Enter fullscreen mode
Exit fullscreen mode
The purpose of this program is to find the largest value in a Vector . Its logic is easy to understand: take the first element as a temporary largest value, then use a loop to compare every element in the Vector . If the current element is greater than the value stored as the largest, assign the current element to largest .
Output:
The largest number is 5
Enter fullscreen mode
Exit fullscreen mode
If a new requirement is added at this point and you need to find the largest value in another Vector , you can still write it using the same logic:
fn main (){ let number_list = vec!…