【发布时间】:2016-07-30 10:19:51
【问题描述】:
为什么我不能在inspect 期间对这个向量进行push 并在skip_while 期间对它执行contains?
我已经为自己的结构 Chain 实现了自己的迭代器,如下所示:
struct Chain {
n: u32,
}
impl Chain {
fn new(start: u32) -> Chain {
Chain { n: start }
}
}
impl Iterator for Chain {
type Item = u32;
fn next(&mut self) -> Option<u32> {
self.n = digit_factorial_sum(self.n);
Some(self.n)
}
}
现在我想做的是take,而迭代器正在生成唯一值。所以我 inspect-ing 链并推送到一个向量,然后在 take_while 范围内检查它:
let mut v = Vec::with_capacity(terms);
Chain::new(i)
.inspect(|&x| {
v.push(x)
})
.skip_while(|&x| {
return v.contains(&x);
})
然而,Rust 编译会吐出这个错误:
error: cannot borrow `v` as immutable because it is also borrowed as mutable [E0502]
...
borrow occurs due to use of `v` in closure
return v.contains(&x);
^
previous borrow of `v` occurs here due to use in closure; the mutable borrow prevents subsequent moves, borrows, or modification of `v` until the borrow ends
.inspect(|&x| {
v.push(x)
})
显然我不理解“借用”的概念。我做错了什么?
【问题讨论】:
-
这个问题可能与您尝试关闭另一个范围内某处的变量有关 (
v)。这在 Rust 中非常重要。所以我们需要查看v的来源、它的声明方式以及在当前范围内如何引用它。 -
@SimonWhitehead 已编辑以包含
v。一定是之前漏掉了。
标签: iterator rust lazy-evaluation borrowing