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

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

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;
    }
}
a10540693 回答:编译错误:无法分配给`self.root.next`,因为它是借来的

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3168756.html

大家都在问