我有一个 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?
}
Run Code Online (Sandbox Code Playgroud)
如何获取当前元素的索引?
我试过了
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
Run Code Online (Sandbox Code Playgroud)
,这个关于这个主题的 SO 答案让我相信我应该使用 for 循环来代替(尽管我可能会误解),因为我并没有试图以任何方式调整原始 vec。
只需使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
610 次 |
| 最近记录: |