Enhanced For Loop
Part of the Fundamentals section of Coddy's Rust journey — lesson 66 of 75.
There are different ways to iterate over an array, here are some of them:
Consider the following array:
let numbers = [1, 2, 3, 4, 5];Direct Iterator:
for num in numbers.iter() {} // Values: 1, 2, 3, 4, 5
Index & Value:
for (index, value) in numbers.iter().enumerate() { } // Values: (0,1), (1,2), (2,3), (3,4), (4,5)
Slices of specific size:
for chunk in numbers.chunks(2) { } // Values: [1,2], [3,4], [5]
Iterate with mutation:
for num in numbers.iter_mut() { *num *= 2; } // Array becomes: [2, 4, 6, 8, 10]
Challenge
EasyCreate a program that processes a shopping list with items and their prices, and provides different views of the data.
The program should:
- Print each item number and price (using enumerate)
- Print the prices in pairs (using chunks) as "bundle deals"
- Apply a 10% discount to all prices (using iter_mut)
- Print the final discounted prices
Cheat sheet
Different ways to iterate over arrays in Rust:
Direct Iterator:
for num in numbers.iter() {}
// Values: 1, 2, 3, 4, 5Index & Value with enumerate:
for (index, value) in numbers.iter().enumerate() { }
// Values: (0,1), (1,2), (2,3), (3,4), (4,5)Slices of specific size with chunks:
for chunk in numbers.chunks(2) { }
// Values: [1,2], [3,4], [5]Iterate with mutation using iter_mut:
for num in numbers.iter_mut() {
*num *= 2;
}
// Array becomes: [2, 4, 6, 8, 10]Try it yourself
fn main() {
let mut prices = [2.75, 1.50, 5.00, 3.5, 4.1, 2.25, 7.9];
println!("Original Prices:");
// TODO: Use enumerate to print each item number and price
// Expected: "Item 1: $2.99" etc.
println!("\nBundle Deals:");
// TODO: Use chunks to print pairs of prices and their sums
// Expected: "Bundle 1: $2.99 + $1.50 = $4.49" etc.
// TODO: Use iter_mut to apply 10% discount to all prices
println!("\nPrices after 10% discount:");
// TODO: Print final prices after discount
// Expected: "$2.69" etc.
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input