当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Rust Iterator.enumerate用法及代码示例


本文简要介绍rust语言中 core::iter::Iterator.enumerate 的用法。

用法

fn enumerate(self) -> Enumerate<Self> where    Self: Sized,

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

返回的迭代器产生对 (i, val) ,其中 i 是迭代的当前索引,而 val 是迭代器返回的值。

enumerate() 将其计数保持为 usize 。如果您想按不同大小的整数进行计数, zip 函数提供了类似的函数。

溢出行为

该方法没有防止溢出,因此枚举超过 usize::MAX 的元素会产生错误的结果或出现Panics。如果启用了调试断言,则保证会出现Panics。

Panics

如果 to-be-returned 索引会溢出 usize ,则返回的迭代器可能会出现Panics。

例子

let a = ['a', 'b', 'c'];

let mut iter = a.iter().enumerate();

assert_eq!(iter.next(), Some((0, &'a')));
assert_eq!(iter.next(), Some((1, &'b')));
assert_eq!(iter.next(), Some((2, &'c')));
assert_eq!(iter.next(), None);

相关用法


注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 core::iter::Iterator.enumerate。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。