请教 rust 的 Borrowing 的一个问题。

2019-11-25 14:54:17 +08:00
 ShangShanXiaShan
use std::collections::LinkedList;

struct MyClass {
    args: Option<Box<MyClass>>
}

impl MyClass {
    fn new() -> Self {
        Self { args: None }
    }
    
    fn set_args(&mut self, args: Box<MyClass>) {
        self.args = Some(args);
    }
}

fn main() {
    let mut list = LinkedList::new();
    let mut root = MyClass::new();

    list.push_back(&mut root);
    while !list.is_empty() {
        let mut new_list = LinkedList::new();
        for item in list {
            // do something
            let mut new_cls = MyClass::new();
            new_list.push_back(&mut new_cls); // `new_cls` does not live long enough
            item.set_args(Box::new(new_cls)); // cannot move out of `new_cls` because it is borrowed
            // do something
        }
        
        list = new_list;
    }
    
}

这样写会报两个错(如注释里面)。我尝试过将 set_args 返回 new_cls 的引用,然后使用这个返回 pushnew_list,来解决这两个问题。但是因为在 set_args 之后,我还需要做一些操作,导致报 "cannot borrow **item as mutable more than once at a time"

我该怎么做才能让 Myclass 和 list 都持有对应的引用? 谢谢。

806 次点击
所在节点    问与答
2 条回复
codehz
2019-11-25 15:03:03 +08:00
你需要 Rc,并且两个容器都得用 Rc
ShangShanXiaShan
2019-11-25 15:32:24 +08:00
@codehz 谢谢大佬,我去试试

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/622923

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX