我有一个带有函数的结构next()
(类似于迭代器,但不是迭代器)。该方法返回修改后的下一个状态(保留原始状态)。所以:fn next(&A) -> A
。
我从一个不需要生命周期的简单结构开始(示例中的结构 A),然后扩展它以添加对新结构(结构 B)的引用。
问题是我现在需要为我的结构指定生命周期,并且由于某种原因我的方法next()
不再起作用。
我怀疑每次迭代的新结构的生命周期仅限于创建它的范围,我不能将它移出这个范围。
是否可以保留我的next()
方法的行为?
#[derive(Clone)]
struct A(u32);
#[derive(Clone)]
struct B<'a>(u32, &'a u32);
impl A {
fn next(&self) -> A {
let mut new = self.clone();
new.0 = new.0 + 1;
new
}
}
impl<'a> B<'a> {
fn next(&self) -> B {
let mut new = self.clone();
new.0 = new.0 + 1;
new
}
}
fn main() {
let mut a = A(0);
for _ in 0..5 {
a = a.next();
}
let x = 0;
let mut b = B(0, &x);
for _ in 0..5 {
b = b.next();
}
}
错误是:
error[E0506]: cannot assign to `b` because it is borrowed
--> src/main.rs:31:9
|
31 | b = b.next();
| ^^^^-^^^^^^^
| | |
| | borrow of `b` occurs here
| assignment to borrowed `b` occurs here