Rust program to use an iterator to traverse the mutable vector elements

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

Problem Solution:

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

Program/Source Code:

The source code to use an iterator to traverse the mutable 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 mutable vector elements

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

Output:

Country names: 
  India
  UK
  USA
  Canada

Explanation:

Here, we created a mutable vector that contains the name of countries. Then we traversed the vector elements using the iter_mut() function and printed them.

Rust Iterator and Closure Programs »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.