编译错误:无法分配给`self.root.next`,因为它是借来的

时间:2019-11-04 06:13:01

标签: rust

我在结构内部引用时遇到麻烦,尤其是关于它们的生命周期。这是重现我的问题的最低代码:

pub struct Node<'a> {
    next: &'a Node<'a>
}

pub struct Tree<'a> {
    root: Node<'a>,
}

impl<'a> Tree<'a> {

    fn add(&'a mut self) {
        self.root.next = &self.root;
    }
}

我收到此错误:

error[E0506]: cannot assign to `self.root.next` because it is borrowed
  --> src/main.rs:27:9
   |
24 | impl<'a> Tree<'a> {
   |      -- lifetime `'a` defined here
...
27 |         self.root.next = &self.root;
   |         ^^^^^^^^^^^^^^^^^----------
   |         |                |
   |         |                borrow of `self.root.next` occurs here
   |         assignment to borrowed `self.root.next` occurs here
   |         assignment requires that `self.root` is borrowed for `'a`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0506`.
error: Could not compile `lifetime`.

To learn more, run the command again with --verbose

-

一些注意事项:这个没有中间Tree的简单版本可以编译:

pub struct Node<'a> {
    next: &'a Node<'a>
}

impl<'a> Node<'a> {

    fn add(&'a mut self) {
        self.next = self;
    }
}

0 个答案:

没有答案