本文介绍了如何根据 Peekable::peek 的结果调用 Peekable::next?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
use std::iter::Peekable;
pub trait AdvanceWhile<I: Iterator> {
fn advance_while<P>(&mut self, predicate: P)
where
P: Fn(&I::Item) -> bool;
}
impl<I: Iterator> AdvanceWhile<I> for Peekable<I> {
fn advance_while<P>(&mut self, predicate: P)
where
P: Fn(&I::Item) -> bool,
{
while let Some(val) = self.peek() {
if predicate(val) {
self.next();
} else {
break;
}
}
}
}
错误:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/main.rs:16:17
|
14 | while let Some(val) = self.peek() {
| ---- first mutable borrow occurs here
15 | if predicate(val) {
16 | self.next();
| ^^^^ second mutable borrow occurs here
...
20 | }
| - first borrow ends here
推荐答案
正如 Lukas Kalbertodt 已经说过的,这是一个借用检查器的限制.这里我想展示一个更易读的版本:
As Lukas Kalbertodt already said, this is a limitation of the borrow checker. Here I would like to show a more readable version:
fn advance_while<P>(&mut self, predicate: P)
where P: Fn(&I::Item) -> bool
{
while let Some(true) = self.peek().map(&predicate) {
self.next();
}
}
这篇关于如何根据 Peekable::peek 的结果调用 Peekable::next?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!