Rust 迭代器:添加索引计数
在 Rust 中,我们可以使用 'enumerate()' 方法创建一个带有当前是第几个的迭代器。
下面是一个示例代码:
fn main() {
let data = vec!['apple', 'banana', 'cherry'];
for (index, item) in data.iter().enumerate() {
println!('Item at index {} is {}', index, item);
}
}
输出结果:
Item at index 0 is apple
Item at index 1 is banana
Item at index 2 is cherry
在这个示例中,我们使用 'data.iter().enumerate()' 创建了一个带有索引的迭代器。'enumerate()' 方法会返回一个元组,其中第一个元素是当前索引,第二个元素是迭代器中的项。然后,我们可以使用 'for' 循环迭代这个元组,并打印出索引和项的值。
希望对你有帮助!
原文地址: https://www.cveoy.top/t/topic/pbMf 著作权归作者所有。请勿转载和采集!