rustHow to create a generator function in Rust?
A generator function in Rust is a function that can be used to generate a sequence of values. It is defined using the yield
keyword.
Example
fn generator() -> impl Iterator<Item = i32> {
let mut i = 0;
loop {
yield i;
i += 1;
}
}
Output example
0
1
2
3
...
Code explanation
fn generator() -> impl Iterator<Item = i32>
: This is the function signature, which defines the return type as an iterator of typei32
.let mut i = 0
: This declares a mutable variablei
and initializes it to0
.yield i
: This is theyield
keyword, which is used to return a value from the generator.i += 1
: This increments the value ofi
by1
.
Helpful links
Related
More of Rust
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to match the end of a line in a Rust regex?
- How to get execution time in Rust
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to convert the keys of a Rust HashMap to a vector?
- How to use regex with bytes in Rust?
See more codes...