Home »
Rust »
Rust Programs
Rust program to iterate the items of the vector using the 'for' loop
Rust | Vector Example: Write a program to iterate the items of the vector using the 'for' loop.
Submitted by Nidhi, on October 24, 2021
Problem Solution:
In this program, we will create a vector of string elements using the new() method then we will add items into the created vector using the push() method and access vector elements using the "for" loop.
Program/Source Code:
The source code to iterate the items of the vector using the "for" loop is given below. The given program is compiled and executed successfully.
// Rust program to iterate the items
// of vector using "for" loop
fn main() {
let mut countries: Vec<&str> = Vec::new();
let mut index:usize=0;
countries.push("INDIA");
countries.push("USA");
countries.push("UK");
countries.push("CANADA");
countries.push("ENGLAND");
println!("Countries are: ");
for item in countries
{
println!(" {} ",item);
}
}
Output:
Countries are:
INDIA
USA
UK
CANADA
ENGLAND
Explanation:
Here, we created a vector using the new() method to store the name of countries. Then we added items into created vector. After that, we iterate vector elements using the "for" loop and printed them.
Rust Vectors Programs »