
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 的引用,然后使用这个返回 push 进 new_list,来解决这两个问题。但是因为在 set_args 之后,我还需要做一些操作,导致报 "cannot borrow **item as mutable more than once at a time"。
我该怎么做才能让 Myclass 和 list 都持有对应的引用? 谢谢。
1 codehz 2019-11-25 15:03:03 +08:00 via Android 你需要 Rc,并且两个容器都得用 Rc |
2 ShangShanXiaShan OP @codehz 谢谢大佬,我去试试 |