loops - 如何在 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。
解决方案
只需使用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
推荐阅读
- javascript - GroupBy 对象数组
- reactjs - 在 React 中连续上下移动图像
- python - 确定投资组合波动率的函数 - Python 函数语法
- node.js - 如何检查用户是否已登录?
- r - 如何用R中的组合特殊字符替换字符串
- javascript - 如何在此 google 脚本/文件上传表单中添加进度条
- python - 此行和第五行之间的 Python 数据框差异
- azure - 无法生成 Azure SAS 连接字符串。怀疑这是“由于未发布端点,某些路由选项被禁用。”
- roku - How to post xml with roUrlTransfer in a Roku App?
- python - 向现有数据框添加一列重复数字