gpt4 book ai didi

rust - 了解 Rc> 在 Rust 中的用法

转载 作者:行者123 更新时间:2023-12-03 11:27:25 32 4
gpt4 key购买 nike

我正在查看一些使用的代码

Rc<RefCell<SomeStruct>>

所以我出去阅读了 Rc 和 RefCell 之间的差异:

以下是选择 Box、Rc 或 RefCell 的原因的概述:

Rc enables multiple owners of the same data; Box and RefCell have single owners.

Box allows immutable or mutable borrows checked at compile time; Rc allows only immutable borrows checked at compile time;

RefCell allows immutable or mutable borrows checked at runtime. Because RefCell allows mutable borrows checked at runtime, you can mutate the value inside the RefCell even when the RefCell is immutable.



因此, Rc 确保 SomeStruct 可供多人同时访问。但我如何访问?我只看到 get_mut 方法,它返回一个可变引用。但是文本解释了“Rc 只允许不可变的借用”。

如果可以以 mut 而不是 mut 方式访问 Rc 的对象,为什么需要 RefCell?

最佳答案

So, Rc makes sure that SomeStruct is accessible by many people at the same time. But how do I access?



通过解引用。如果您有 x 类型的变量 Rc<...> ,则可以使用 *x 访问内部值。在许多情况下,这是隐式发生的;例如,您可以简单地使用 x 调用 x.method(...) 上的方法。

I only see the get_mut method, which returns a mutable reference. But the text explained that "Rc allows only immutable borrows".


get_mut() 方法可能比 Rc 只允许不可变借用的解释更新。此外,如果当前只有一个内部值的所有者,即如果您目前首先不需要 Rc,它只会返回一个可变借用。一旦有多个所有者, get_mut() 将返回 None

If it's possible to access Rc's object in mut and not mut way, why a RefCell is needed?



即使存在多个所有者, RefCell 也将允许您获得可变访问权限,即使您只持有对 RefCell 的共享引用。它会在运行时动态检查在任何给定时间只存在一个可变引用,并且如果您请求第二个并发引用(或分别返回和 try_borrow 方法的错误),它会发生 panic 。 Rc 不提供此功能。

总而言之, Rc 为您提供共享所有权。内部值有多个所有者,只要至少有一个所有者仍然持有它,引用计数就可以确保数据保持事件状态。如果您的数据没有明确的单一所有者,这将非常有用。 RefCell 为您提供内部可变性,即您可以在运行时动态借用内部值,即使使用共享引用也可以修改它。 Rc<RefCell<...>> 组合为您提供了两者的组合 - 一个具有多个所有者的值,可以由任何一个所有者可变地借用。

更详细的可以阅读 Rust 书的相关章节:
  • Rc<T> , the Reference Counted Smart Pointer
  • RefCell<T> and the Interior Mutability Pattern
  • 关于rust - 了解 Rc<RefCell<SomeStruct>> 在 Rust 中的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997859/

    32 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com