【问题标题】:How do I get the index of the current element in a for loop in Rust?如何在 Rust 的 for 循环中获取当前元素的索引?
【发布时间】:2021-05-23 02:10:34
【问题描述】:

我有一个 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

this SO answer on the subject 让我相信我应该改用 for 循环(尽管我可能会误解),因为我并没有试图以任何方式调整原始 vec。

【问题讨论】:

  • 请提供完整的错误信息..
  • enumerate() 产生的元组顺序相反,即(i, el) 而不是(el, i)。请参阅Examples section

标签: loops rust


【解决方案1】:

只需使用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

【讨论】:

    猜你喜欢
    • 2013-02-15
    • 1970-01-01
    • 2021-10-30
    • 2011-03-26
    • 2023-04-05
    • 1970-01-01
    • 2010-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多