When to use Rc vs Box?
我有以下同时使用
1 2 3 4 5 6 7 8 9 10 11 12 13 | use std::rc::Rc; fn main() { let a = Box::new(1); let a1 = &a; let a2 = &a; let b = Rc::new(1); let b1 = b.clone(); let b2 = b.clone(); println!("{} {}", a1, a2); println!("{} {}", b1, b2); } |
游乐场链接
1 2 3 4 5 6 7 8 9 | use std::rc::Rc; fn main() { let mut a = Box::new(1); let mut b = Rc::new(1); *a = 2; // works *b = 2; // doesn't } |
此外,
最重要的是,它们用于不同的用途:如果不需要共享访问权限,请使用
看看描述中给出的示例,我认为这里的真正问题是"何时使用
在
用不同的方式讲,与
作为一个具体示例,以下内容是有效的:
1 2 3 4 5 6 7 8 9 10 11 12 | use std::rc::Rc; fn main() { let rc_clone; { let rc = Rc::new(1); rc_clone = rc.clone(); // rc gets out of scope here but as a"shared owner", rc_clone // keeps the underlying data alive. } println!("{}", rc_clone); // Ok. } |
但这不是:
1 2 3 4 5 6 7 8 9 10 | fn main() { let b_ref; { let b = Box::new(1); b_ref = &b; // b gets out of scope here and since it is the only owner, // the underlying data gets dropped. } println!("{}", b_ref); // Compilation error: `b` does not live long enough. } |