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 use non-capturing groups in Rust regex?
- How to use Unicode in a regex in Rust?
- How to replace a capture group using Rust regex?
- How to match whitespace with a regex in Rust?
- How to replace all matches using Rust regex?
- How to split a string with Rust regex?
- How to generate struct from json in Rust
- How to replace strings using Rust regex?
- Example of yield_now in Rust?
- How to get pointer to variable in Rust
See more codes...