Cycle Repeats An Iterator With A Take Bound
Turn a finite slice iterator into an endless stream with cycle, then bound consumption with take and hop around the stream with nth.
Code
fn main() {
let suits = ["hearts", "diamonds", "clubs", "spades"];
// cycle:有限序列变无限流;take 提供边界,enumerate 顺手编号
let deal: Vec<(&str, usize)> = suits
.iter()
.cycle()
.enumerate()
.take(9)
.map(|(index, suit)| (*suit, index + 1))
.collect();
println!("{deal:?}");
// 无限流用 next/nth 逐个取:一圈 4 个,循环往复
let mut round = suits.iter().cycle();
println!("first: {:?}", round.next());
let _ = round.nth(3); // 消费掉第 2~4 个
println!("fifth: {:?}", round.next());
}How it works
Count the function main as the entire surface area of Cycle Repeats An Iterator With A Take Bound.
Putting it to use
Running the file prints labeled results such as first:, fifth: — each operation’s effect is visible in the output.
Core lines
let mut round = suits.iter().cycle();
.map(|(index, suit)| (*suit, index + 1))
.collect();
Interactive Tools for This Topic
FAQ
- What does Cycle Repeats An Iterator With A Take Bound print when run?
- The script runs standalone; its 2 labeled outputs include `first:`, `fifth:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.