rustHow to yield return in Rust?
Rust provides the yield
keyword to allow a function to return multiple values. It is used to create an iterator that can be used to iterate over a collection of values.
Example code
fn main() {
let mut iter = yield_return();
for i in iter {
println!("{}", i);
}
}
fn yield_return() -> impl Iterator<Item = i32> {
let mut i = 0;
loop {
yield i;
i += 1;
}
}
Output example
0
1
2
3
4
...
Code explanation
fn main()
: This is the main function that will be called when the program is executed.let mut iter = yield_return()
: This creates an iterator from theyield_return
function.for i in iter
: This loop iterates over the values returned by theyield_return
function.yield i
: This is theyield
keyword, which returns the value ofi
to the iterator.i += 1
: This increments the value ofi
for the next iteration.
Helpful links
Related
- How to yield a thread in Rust?
- Yield example in Rust
- Yield generator in Rust
- How to use an async yield in Rust?
- How to implement a generator trait in Rust?
- Example of yield_now in Rust?
- How to use an async generator in Rust?
- How to use a generator map in Rust?
- How to create a generator iterator in Rust?
More of Rust
- How to replace a capture group using Rust regex?
- How to calculate the sum of a Rust slice?
- How do I create an array of strings in Rust?
- How to replace all matches using Rust regex?
- How to use regex to match a double quote in Rust?
- Hashshet example in Rust
- How to use regex captures in Rust?
- How to convert JSON to a struct in Rust?
- How to pop an element from a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
See more codes...