Rc<RefCell<T>和Rc<RefCell<T>之间有什么区别?和RefCell Rc T ? [英] What is the difference between Rc<RefCell<T>> and RefCell<Rc<T>>?

查看:44
本文介绍了Rc<RefCell<T>和Rc<RefCell<T>之间有什么区别?和RefCell Rc T ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust 文档涵盖了 Rc> 相当广泛,但没有涉及 RefCell>,我现在就是遇到.

The Rust documentation covers Rc<RefCell<T>> pretty extensively but doesn't go into RefCell<Rc<T>>, which I am now encountering.

这些是否有效地给出了相同的结果?它们之间有重要区别吗?

Do these effectively give the same result? Is there an important difference between them?

推荐答案

这些是否有效地给出了相同的结果?

Do these effectively give the same result?

它们非常不同.

Rc 是一个拥有共享所有权的指针,而 RefCell 提供内部可变性.它们的组成顺序对它们的使用方式有很大的不同.

Rc is a pointer with shared ownership while RefCell provides interior mutability. The order in which they are composed makes a big difference to how they can be used.

通常,您将它们组合为 Rc>;整个事情都是共享的,每个共享的所有者都可以改变内容.由于内部数据是共享的,因此外部Rc 的所有共享所有者都会看到更改内容的效果.

Usually, you compose them as Rc<RefCell<T>>; the whole thing is shared and each shared owner gets to mutate the contents. The effect of mutating the contents will be seen by all of the shared owners of the outer Rc because the inner data is shared.

除非通过引用,您不能共享 RefCell>,因此此配置在如何使用方面受到更多限制.为了改变内部数据,您需要从外部 RefCell 可变地借用,但随后您就可以访问 immutable Rc>.改变它的唯一方法是用完全不同的 Rc 替换它.例如:

You can't share a RefCell<Rc<T>> except by reference, so this configuration is more limited in how it can be used. In order to mutate the inner data, you would need to mutably borrow from the outer RefCell, but then you'd have access to an immutable Rc. The only way to mutate it would be to replace it with a completely different Rc. For example:

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

没有办法改变ab 中的值.这似乎远没有 Rc> 有用.

There is no way to mutate the values in a and b. This seems far less useful than Rc<RefCell<T>>.

这篇关于Rc&lt;RefCell&lt;T&gt;和Rc&lt;RefCell&lt;T&gt;之间有什么区别?和RefCell Rc T ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆