首页 > 解决方案 > 如何在 Rust 的 for 循环中获取当前元素的索引?

问题描述

我有一个 for 循环:

let list: &[i32]= vec!(1,3,4,17,81);


for el in list {
 println!("The current element is {}", el);
 println!("The current index is {}", i);// <- How do I get the current index?
}

如何获取当前元素的索引?

我努力了

for el, i in list

for {el, i} in list

for (el, i) in list.enumerate()

我能够使用 vec 的映射访问迭代器,但收到一个错误:

unused `std::iter::Map` that must be used

note: `#[warn(unused_must_use)]` on by default
note: iterators are lazy and do nothing unless consumed

这个关于这个主题的答案让我相信我应该使用 for 循环(尽管我可能会误解),因为我没有试图以任何方式调整原始 vec。

标签: loopsrust

解决方案


只需使用enumerate

创建一个迭代器,它给出当前迭代计数以及下一个值。

fn main() {
    let list: &[i32] = &vec![1, 3, 4, 17, 81];

    for (i, el) in list.iter().enumerate() {
        println!("The current element is {}", el);
        println!("The current index is {}", i);
    }
}

输出:

The current element is 1
The current index is 0
The current element is 3
The current index is 1
The current element is 4
The current index is 2
The current element is 17
The current index is 3
The current element is 81
The current index is 4

推荐阅读