Rc <RefCell <T >>和RefCell <Rc <T >>有什么区别?

时间:2019-08-05 23:17:50

标签: rust smart-pointers interior-mutability

Rust文档涵盖了Rc<RefCell<T>>的广泛内容,但没有涉及到RefCell<Rc<T>>,我现在遇到了。

这些有效地产生相同的结果吗?它们之间有重要区别吗?

1 个答案:

答案 0 :(得分:3)

  

这些有效地产生相同的结果吗?

它们非常不同。

origin = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default=self.get_default_origin, related_name='origin') destination = models.ForeignKey(Location, on_delete = models.SET_DEFAULT, default=self.get_default_destination, related_name='destination') 是具有共享所有权的指针,而Rc提供了内部可变性。它们的组成顺序与使用方式大不相同。

通常,您将它们组成为RefCell;整个事情都是共享的,每个共享的所有者都可以更改其内容。外部Rc<RefCell<T>>的所有共享所有者都会看到更改内容的效果,因为内部数据是共享的。

除参考外,您不能共享Rc,因此此配置在使用方式上受到更多限制。为了对内部数据进行变异,您需要从外部RefCell<Rc<T>>变异地借用,但是随后您就可以访问不可变 RefCell。进行更改的唯一方法是将其替换为完全不同的Rc。例如:

Rc

无法对let a = Rc::new(1); let b = Rc::new(2); let c = RefCell::new(Rc::clone(&a)); let d = RefCell::new(Rc::clone(&a)); *d.borrow_mut() = Rc::clone(&b); // this doesn't affect c a中的值进行突变。这似乎远没有b有用。