V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
ShangShanXiaShan
V2EX  ›  问与答

请教 rust 的 Borrowing 的一个问题。

  •  
  •   ShangShanXiaShan · 2019-11-25 14:54:17 +08:00 · 772 次点击
    这是一个创建于 1585 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 都持有对应的引用? 谢谢。

    2 条回复    2019-11-25 15:32:24 +08:00
    codehz
        1
    codehz  
       2019-11-25 15:03:03 +08:00 via Android   ❤️ 1
    你需要 Rc,并且两个容器都得用 Rc
    ShangShanXiaShan
        2
    ShangShanXiaShan  
    OP
       2019-11-25 15:32:24 +08:00
    @codehz 谢谢大佬,我去试试
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1026 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 22:31 · PVG 06:31 · LAX 15:31 · JFK 18:31
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.