Rust program to use an iterator to read values from an array

Rust | Iterator and Closure Example: Write a program to demonstrate the use of an iterator to read values from an array.
Submitted by Nidhi, on November 22, 2021

Problem Solution:

In this program, we will create an array of integers and read values from an array using iterator and print elements.

Program/Source Code:

The source code to use an iterator to read values from an array is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to use of an iterator 
// to read values from an array

fn main() 
{
   let int_arr = [50,40,30,20,10];
   let mut itr = int_arr.iter(); 
   
   println!("Array elements are: ");
   println!("{:?}",itr.next());
   println!("{:?}",itr.next());
   println!("{:?}",itr.next());
   println!("{:?}",itr.next());
   println!("{:?}",itr.next());
}

Output:

Array elements are: 
Some(50)
Some(40)
Some(30)
Some(20)
Some(10)

Explanation:

Here, we created an array of integers. Then we read the elements of an array using iterator and printed the result.

Rust Iterator and Closure Programs »





Comments and Discussions!

Load comments ↻





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