Introduction
We use iteration to look at each item in a group one by one. This helps us do something with every item easily.
We use iteration to look at each item in a group one by one. This helps us do something with every item easily.
for item in collection { // use item here }
for starts the loop.
item is each element from the collection, one at a time.
let numbers = [1, 2, 3]; for num in numbers { println!("{}", num); }
let words = vec!["apple", "banana", "cherry"]; for word in &words { println!("{}", word); }
let mut sum = 0; let values = [10, 20, 30]; for val in values { sum += val; } println!("Sum is {}", sum);
This program goes through each fruit and prints a sentence about liking it.
fn main() {
let fruits = ["apple", "banana", "cherry"];
for fruit in &fruits {
println!("I like {}", fruit);
}
}You can use for loops with arrays, vectors, and other collections.
Using &collection lets you borrow items without taking ownership.
Remember, Rust's for loop automatically handles the iterator for you.
Use for loops to visit each item in a collection.
It helps you do the same action on every element easily.
Works with arrays, vectors, and more.
let numbers = [1, 2, 3];
for num in numbers {
println!("{}", num);
}v in Rust?let v = vec![10, 20, 30];
let mut sum = 0;
for &num in &v {
sum += num;
}
println!("{}", sum);let arr = [1, 2, 3];
for num in arr {
num += 1;
println!("{}", num);
}let words = vec!["apple", "banana", "cherry"];. How do you create a new vector containing the lengths of each word using iteration?Pass the test and this pattern moves unknown