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
- How to yield return in Rust?
- Yield example in Rust
- How to use an async yield in Rust?
- How to yield a thread in Rust?
- How to use an async generator in Rust?
- How to create a generator iterator in Rust?
- How to use a generator map in Rust?
- Generator example in Rust
- How to create a generator function in Rust?
More of Rust
- How do I declare multiple variables in Rust?
- How to get time from milliseconds in Rust
- How to pretty print a struct in Rust
- How to serialize struct to json in Rust
- How to check a value for null in Rust
- How to iterate an array with index in Rust
- Regex example to match multiline string in Rust?
- How to replace all using regex in Rust?
- How to use regex to match a double quote in Rust?
- How do I print the address of a variable in Rust?
See more codes...