rustHow to create a generator iterator in Rust?
Creating a generator iterator in Rust is a simple process. To create a generator iterator, you must first define a function that returns a yield
expression. The yield
expression will return a value each time the generator is called.
Example code
fn generator() -> impl Iterator<Item = i32> {
let mut i = 0;
loop {
yield i;
i += 1;
}
}
let mut gen = generator();
println!("{}", gen.next().unwrap());
Output example
0
Code explanation
fn generator() -> impl Iterator<Item = i32>
: This line defines a function calledgenerator
that returns an iterator of typei32
.let mut i = 0
: This line declares a mutable variablei
and sets its initial value to0
.loop {
: This line starts an infinite loop.yield i
: This line yields the value ofi
each time the generator is called.i += 1
: This line increments the value ofi
by1
each time the loop is executed.let mut gen = generator()
: This line creates a mutable variablegen
and assigns it the value returned by thegenerator
function.println!("{}", gen.next().unwrap())
: This line prints the value returned by thenext
method of thegen
variable.
Helpful links
Related
More of Rust
- How to use regex with bytes in Rust?
- How to use regex to match a double quote in Rust?
- How to get all values from a Rust HashMap?
- How to use negation in Rust regex?
- How to match the end of a line in a Rust regex?
- How to use a Rust HashMap in a struct?
- How to iterate through hashmap keys in Rust
- How to get an entry from a HashSet in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to modify an existing entry in a Rust HashMap?
See more codes...