实现说明
cycle 无限循环迭代器以函数 main为骨架。
使用要点
- 每一步打印都带着自己的标签:
first:、fifth:。
常见问题
运行「cycle 无限循环迭代器」会打印什么?
不用做任何设置,直接把文件跑完——输出里的 first:、fifth: 标签标明各步骤。
核心语句
let mut round = suits.iter().cycle();
.map(|(index, suit)| (*suit, index + 1))
.collect();
代码示例
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());
}