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.
Similar Reads
Rust - Drop Trait Drop trait lets us customize what happens when a value is about to go out of scope. Drop trait is important to the smart pointer pattern. Drop trait functionality is used when implementing a smart pointer. For example, Box<T> customizes Drop to deallocate the space on the heap that the box po
3 min read
Rust - Deref Trait Deref<T> trait in Rust is used for customizing dereferencing operator (*) behavior. Implementing the Deref <T> treats the smart pointer as a reference. Therefore, any code that references the deref trait would also refer to smart pointers. Regular References in Deref Trait:Regular refer
2 min read
Rust impl Trait In Rust, there is a concept of impl trait. Â impl Trait is used to implement functionality for types and is generally used in function argument positions or return positions. It is used in scenarios where our function returns a single type value. In the impl trait, we always specify the impl keyword
2 min read
Rust - Clone Trait In Rust, we have a concept of clone trait. Clone traits have the ability to duplicate objects explicitly. We can make anything copy with the Clone Trait. Syntax: //pub refers to public trait pub trait Clone {Â Â fn clone(&self) -> Self; Â Â fn clone_from_trait(&mut self, source: &Self)
2 min read
Rust - Generic Traits Rust is an extremely fast programming language that supports speed, concurrency, as well as multithreading. In Rust, we have a concept of Generic Traits where Generics are basically an abstraction of various properties, and Traits are basically used for combining generic types for constraining types
2 min read