rust for loop
Rust for Loop
In Rust, the for
loop is used to iterate over a collection of items. It is commonly used to iterate over arrays, vectors, ranges, and other iterable objects.
The syntax for a for
loop in Rust is as follows:
for item in collection {
// Code to be executed for each item
}
Here, item
is a variable that represents each item in the collection, and collection
is the iterable object.
Example:
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for number in numbers {
println!("Number: {}", number);
}
}
In this example, we have a vector numbers
containing integers. The for
loop iterates over each item in the vector and prints it.
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Note that the for
loop takes ownership of the collection by default. If you want to iterate over the collection without taking ownership, you can use the &
symbol before the collection variable:
fn main() {
let numbers = vec![1, 2, 3, 4, 5];
for &number in &numbers {
println!("Number: {}", number);
}
}
In this case, we use &numbers
to borrow a reference to the vector, and &number
to borrow a reference to each item in the vector.
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
This allows us to iterate over the collection without taking ownership.
I hope this helps! Let me know if you have any further questions.