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_returnfunction.for i in iter: This loop iterates over the values returned by theyield_returnfunction.yield i: This is theyieldkeyword, which returns the value ofito the iterator.i += 1: This increments the value ofifor the next iteration.
Helpful links
Related
More of Rust
- How to match a URL with a regex in Rust?
- How to use regex to match a double quote in Rust?
- How to find the first match in a Rust regex?
- How to perform matrix operations in Rust?
- How to sort a Rust HashMap?
- How to match the end of a line in a Rust regex?
- How to make regex case insensitive in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to create a Rust HashMap from a vector of tuples?
- How to get all values from a Rust HashMap?
See more codes...