Rust program to use an iterator to traverse the vector elements

Rust | Iterator and Closure Example: Write a program to demonstrate the use of an iterator to traverse the vector elements.
Submitted by Nidhi, on November 22, 2021

Problem Solution:

In this program, we will create a vector that contains the name of countries. Then we will traverse vector elements using iterator.

Program/Source Code:

The source code to use an iterator to traverse the vector elements is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to use of an iterator to 
// traverse the vector elements

fn main() 
{
   	let countries = vec!["India", "UK", "USA", "Canada"];
   
   	println!("Country names: ");
   	for country in countries.into_iter() 
   	{
		println!("  {}",country);
   	}
}

Output:

Country names: 
  India
  UK
  USA
  Canada

Explanation:

Here, we created a vector that contains the name of countries. Then we traversed the vector elements and printed them.

Rust Iterator and Closure Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.