一个 for 循环如何借用迭代器? [英] How does one have a for loop borrow the iterator?
本文介绍了一个 for 循环如何借用迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何让 for
... in
循环借用它正在操作的迭代器?例如:
How does one have a for
... in
loop borrow the iterator it is operating over? For example:
let x = vec![1, 2, 3, 4];
let i = x.iter();
for a1 in i { break; } // iterate over just one "i"
for a2 in i { break; } // continue iterating through "i" here
您不能简单地将 &i
赋予 for,因为这样就无法将 &Iterator
转换为 Iterator
> 对象.
You can't simply give &i
to the for, because then it can't convert the &Iterator
to an Iterator
object.
推荐答案
您可以使用 Iterator::by_ref
借用迭代器,借用结束后继续使用:
You can use Iterator::by_ref
to borrow the iterator and continue to use it after the borrow ends:
fn main() {
let x = vec![1, 2, 3, 4];
let mut i = x.iter();
for _ in i.by_ref() { break; } // iterate over just one "i"
for _ in i.by_ref() { break; } // continue iterating through "i" here
assert_eq!(Some(&3), i.next())
}
这篇关于一个 for 循环如何借用迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文