Open In App

Rust – Iterator Trait

Last Updated : 11 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Rust is a systems programming language focusing on speed, concurrency, and ensuring safe code. The iterator trait in Rust is used to iterate over Rust collections like arrays.

Syntax:

//pub refers to the trait being declared public

pub trait Iterator {

// type refers to the elements type over which it is being iterated.
   type Item;
}

While implementing the implement trait, we define a method that is defined for the next elements in the item that are defined either by the user or automatically defined.

Example 1: 

Rust




//  Rust program for Implementing a function 
// over a sequence that returns None and some
struct GFG {
    current_value: u32,
    next_value: u32,
}
impl Iterator for GFG {
    type Item = u32;
      
fn next(&mut self) -> Option<Self::Item> {
        let present_value = self.current_value;
  
        self.current_value = self.next_value;
        self.next_value = present_value + self.next_value;
  
        Some(present_value)
    }
}
  
fn main() {
  
    // `2020..2023` is an `Iterator` that generates: 2020, 2021, and 2022.
    let mut defined_sequence = 2020..2023;
  
    println!("Calling the next calls on sequence");
    println!("{:?}", defined_sequence.next());
    println!("{:?}", defined_sequence.next());
    println!("{:?}", defined_sequence.next());
    println!("{:?}", defined_sequence.next());
      
    }


Output:

 

Explanation:

In this example, we define a struct GFG that has two values: current_value and next_value both having u32 values (unsigned 32-bit). We use impl for the iterator trait and declare the type Item has u32 type. We are implementing an iterator trait for GFG.

Now, we declare the function as next and then define present_value (variable) and assign the current_variable as self. Now, the current_value will point to the next_value in the sequence and simultaneously add it to the present value just as a Fibonacci sequence generation. If there is no endpoint in the sequence the Iterator does return None and Some are returned all the time.

Here, we define the sequence using `.current_variable` and `.next_variable’. The return type is `Option<T> when ‘Iterator’ is finished otherwise ‘None’ is returned or else next_value would be wrapped in ‘Some’ is returned. Self::Item is used in the return type so that the type can be changed without having the need to function parameters.

Here, we define an iterator and assign it as mutable (define_sequence) and then we call it using the next function by passing it as a parameter.

Example 2: 

Rust




// Rust program for Iterating over Array 
fn main(){
       
 let arr = [10, 20, 30, 40, 50];
    println!("Iterating the following array using Iterator:");
    for num in arr.iter() {
        print!("{} ", num);
    }
}


Output:

 

Explanation:

In this example, we have an array that has a defined number of elements. The `iter` method produces an `Iterator` over the array. 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads