rustYield generator in Rust
Yield generator in Rust is a feature that allows a function to pause its execution and return a value to the caller. It is similar to a generator in Python, but with a few differences.
Example code
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 declares a function namedgenerator
that returns an iterator of typei32
. -
let mut i = 0
: This declares a mutable variablei
and initializes it to0
. -
yield i
: This pauses the execution of the function and returns the value ofi
to the caller. -
i += 1
: This increments the value ofi
by1
.
Helpful links
Related
More of Rust
- How to replace strings using Rust regex?
- How to get a capture group using Rust regex?
- How to use regex lookahead in Rust?
- How to match the end of a line in a Rust regex?
- How to use regex to match a double quote in Rust?
- How to match whitespace with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to find the first match in a Rust regex?
- How to escape dots with regex in Rust?
See more codes...