Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help


x-i18n: generated_at: “2026-03-01T14:36:13Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 44b89630fd7ba91ef3916854e849623118219d900adb94ad1e13a870a3dba8ed source_path: ch15-05-interior-mutability.md workflow: 16

RefCell<T> 与内部可变性模式 (RefCell<T> and the Interior Mutability Pattern)

RefCell<T> and the Interior Mutability Pattern

“内部可变性 (Interior mutability)”是 Rust 中的一种设计模式,它允许你即使在存在该数据的不可变引用时也可以修改数据;通常,借用规则是不允许这种操作的。为了修改数据,该模式在数据结构内部使用了 unsafe(不安全)代码来绕过 Rust 通常控制修改和借用的规则。不安全代码向编译器表明,我们是在手动检查规则,而不是依赖编译器为我们检查;我们将在第 20 章更多地讨论不安全代码。

Interior mutability is a design pattern in Rust that allows you to mutate data even when there are immutable references to that data; normally, this action is disallowed by the borrowing rules. To mutate data, the pattern uses unsafe code inside a data structure to bend Rust’s usual rules that govern mutation and borrowing. Unsafe code indicates to the compiler that we’re checking the rules manually instead of relying on the compiler to check them for us; we will discuss unsafe code more in Chapter 20.

只有当我们能确保在运行时遵循借用规则时,即使编译器无法保证这一点,我们才能使用采用了内部可变性模式的类型。所涉及的 unsafe 代码随后会被包裹在一个安全的 API 中,而外部类型仍然是不可变的。

We can use types that use the interior mutability pattern only when we can ensure that the borrowing rules will be followed at runtime, even though the compiler can’t guarantee that. The unsafe code involved is then wrapped in a safe API, and the outer type is still immutable.

让我们通过研究遵循内部可变性模式的 RefCell<T> 类型来探索这个概念。

Let’s explore this concept by looking at the RefCell<T> type that follows the interior mutability pattern.

在运行时强制执行借用规则 (Enforcing Borrowing Rules at Runtime)

Enforcing Borrowing Rules at Runtime

Rc<T> 不同, RefCell<T> 类型代表对其持有的数据的单一所有权。那么,是什么让 RefCell<T> 与像 Box<T> 这样的类型不同呢?回想一下你在第 4 章中学到的借用规则:

Unlike Rc<T>, the RefCell<T> type represents single ownership over the data it holds. So, what makes RefCell<T> different from a type like Box<T>? Recall the borrowing rules you learned in Chapter 4:

  • 在任何给定时间,你“要么”拥有一个可变引用,“要么”拥有任意数量的不可变引用(但不能两者都有)。

  • 引用必须始终有效。

  • At any given time, you can have either one mutable reference or any number of immutable references (but not both).

  • References must always be valid.

对于引用和 Box<T> ,借用规则的不变量是在编译时强制执行的。而对于 RefCell<T> ,这些不变量是在“运行时”强制执行的。对于引用,如果你违反了这些规则,你会得到一个编译器错误。对于 RefCell<T> ,如果你违反了这些规则,你的程序将引发恐慌并退出。

With references and Box<T>, the borrowing rules’ invariants are enforced at compile time. With RefCell<T>, these invariants are enforced at runtime. With references, if you break these rules, you’ll get a compiler error. With RefCell<T>, if you break these rules, your program will panic and exit.

在编译时检查借用规则的优势在于,错误会在开发过程的早期被发现,并且由于所有的分析都已预先完成,因此不会对运行时性能产生影响。出于这些原因,在大多数情况下,在编译时检查借用规则是最佳选择,这就是 Rust 将其设为默认设置的原因。

The advantages of checking the borrowing rules at compile time are that errors will be caught sooner in the development process, and there is no impact on runtime performance because all the analysis is completed beforehand. For those reasons, checking the borrowing rules at compile time is the best choice in the majority of cases, which is why this is Rust’s default.

相比之下,在运行时检查借用规则的优势在于,它允许某些内存安全的场景,而这些场景在编译时检查中是被禁止的。静态分析(如 Rust 编译器)本质上是保守的。通过分析代码,有些代码属性是无法检测到的:最著名的例子是停机问题 (Halting Problem),这超出了本书的范围,但它是一个值得研究的有趣话题。

The advantage of checking the borrowing rules at runtime instead is that certain memory-safe scenarios are then allowed, where they would’ve been disallowed by the compile-time checks. Static analysis, like the Rust compiler, is inherently conservative. Some properties of code are impossible to detect by analyzing the code: The most famous example is the Halting Problem, which is beyond the scope of this book but is an interesting topic to research.

因为某些分析是不可能的,如果 Rust 编译器无法确定代码符合所有权规则,它可能会拒绝一个正确的程序;从这个意义上说,它是保守的。如果 Rust 接受了一个不正确的程序,用户就无法信任 Rust 所做的保证。然而,如果 Rust 拒绝了一个正确的程序,虽然会给程序员带来不便,但不会发生灾难性的后果。当你确信你的代码遵循了借用规则,但编译器无法理解和保证这一点时, RefCell<T> 类型就派上用场了。

Because some analysis is impossible, if the Rust compiler can’t be sure the code complies with the ownership rules, it might reject a correct program; in this way, it’s conservative. If Rust accepted an incorrect program, users wouldn’t be able to trust the guarantees Rust makes. However, if Rust rejects a correct program, the programmer will be inconvenienced, but nothing catastrophic can occur. The RefCell<T> type is useful when you’re sure your code follows the borrowing rules but the compiler is unable to understand and guarantee that.

类似于 Rc<T>RefCell<T> 仅用于单线程场景,如果你尝试在多线程上下文中使用它,它会给你一个编译时错误。我们将在第 16 章讨论如何在多线程程序中获得 RefCell<T> 的功能。

Similar to Rc<T>, RefCell<T> is only for use in single-threaded scenarios and will give you a compile-time error if you try using it in a multithreaded context. We’ll talk about how to get the functionality of RefCell<T> in a multithreaded program in Chapter 16.

这里回顾一下选择 Box<T>Rc<T>RefCell<T> 的原因:

Here is a recap of the reasons to choose Box<T>, Rc<T>, or RefCell<T>:

  • Rc<T> 允许同一数据拥有多个所有者; Box<T>RefCell<T> 则只有一个所有者。

  • Box<T> 允许在编译时检查不可变或可变借用; Rc<T> 仅允许在编译时检查不可变借用; RefCell<T> 允许在运行时检查不可变或可变借用。

  • 因为 RefCell<T> 允许在运行时检查可变借用,所以即使当 RefCell<T> 是不可变的时,你也可以修改其内部的值。

  • Rc<T> enables multiple owners of the same data; Box<T> and RefCell<T> have single owners.

  • Box<T> allows immutable or mutable borrows checked at compile time; Rc<T> allows only immutable borrows checked at compile time; RefCell<T> allows immutable or mutable borrows checked at runtime.

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

在不可变值内部修改值就是内部可变性模式。让我们看一个内部可变性有用的场景,并研究它是如何实现的。

Mutating the value inside an immutable value is the interior mutability pattern. Let’s look at a situation in which interior mutability is useful and examine how it’s possible.

使用内部可变性 (Using Interior Mutability)

Using Interior Mutability

借用规则的一个后果是,当你有一个不可变值时,你不能对其进行可变借用。例如,这段代码无法通过编译:

A consequence of the borrowing rules is that when you have an immutable value, you can’t borrow it mutably. For example, this code won’t compile:

{{#rustdoc_include ../listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/src/main.rs}}

如果你尝试编译这段代码,你会得到以下错误:

If you tried to compile this code, you’d get the following error:

{{#include ../listings/ch15-smart-pointers/no-listing-01-cant-borrow-immutable-as-mutable/output.txt}}

然而,在某些情况下,一个值在它的方法内部修改自身,但对其他代码表现为不可变是非常有用的。值的方法之外的代码将无法修改该值。使用 RefCell<T> 是获得内部可变性能力的一种方式,但 RefCell<T> 并没有完全绕过借用规则:编译器中的借用检查器允许这种内部可变性,而借用规则改为在运行时进行检查。如果你违反了规则,你将得到一个 panic! 而不是编译器错误。

However, there are situations in which it would be useful for a value to mutate itself in its methods but appear immutable to other code. Code outside the value’s methods would not be able to mutate the value. Using RefCell<T> is one way to get the ability to have interior mutability, but RefCell<T> doesn’t get around the borrowing rules completely: The borrow checker in the compiler allows this interior mutability, and the borrowing rules are checked at runtime instead. If you violate the rules, you’ll get a panic! instead of a compiler error.

让我们通过一个实际的例子,看看我们可以如何使用 RefCell<T> 来修改一个不可变值,并了解为什么这很有用。

Let’s work through a practical example where we can use RefCell<T> to mutate an immutable value and see why that is useful.

使用模拟对象进行测试 (Testing with Mock Objects)

有时在测试期间,程序员会使用一种类型代替另一种类型,以便观察特定行为并断言其实现是否正确。这种占位符类型被称为“测试双倍 (test double)”。可以将其理解为电影制作中的替身演员(stunt double),某个人介入并代替演员完成一场特别棘手的戏。当我们运行测试时,测试双倍会替代其他类型。 “模拟对象 (Mock objects)” 是一种特定类型的测试双倍,它记录测试期间发生的事情,以便你可以断言正确的动作确实发生了。

Sometimes during testing a programmer will use a type in place of another type, in order to observe particular behavior and assert that it’s implemented correctly. This placeholder type is called a test double. Think of it in the sense of a stunt double in filmmaking, where a person steps in and substitutes for an actor to do a particularly tricky scene. Test doubles stand in for other types when we’re running tests. Mock objects are specific types of test doubles that record what happens during a test so that you can assert that the correct actions took place.

Rust 没有像其他语言那样具有“对象”的概念,并且 Rust 在其标准库中也没有像其他一些语言那样内置模拟对象功能。然而,你绝对可以创建一个结构体来实现与模拟对象相同的目的。

Rust doesn’t have objects in the same sense as other languages have objects, and Rust doesn’t have mock object functionality built into the standard library as some other languages do. However, you can definitely create a struct that will serve the same purposes as a mock object.

这是我们要测试的场景:我们将创建一个库,它跟踪一个值相对于最大值的进度,并根据当前值与最大值的接近程度发送消息。例如,该库可以用来跟踪用户被允许进行的 API 调用数量配额。

Here’s the scenario we’ll test: We’ll create a library that tracks a value against a maximum value and sends messages based on how close to the maximum value the current value is. This library could be used to keep track of a user’s quota for the number of API calls they’re allowed to make, for example.

我们的库仅提供跟踪值与最大值的接近程度以及在什么时间应该发送什么消息的功能。使用我们库的应用程序应提供发送消息的机制:应用程序可以直接向用户显示消息、发送电子邮件、发送短信或执行其他操作。库不需要了解这些细节。它只需要一些实现了我们将提供的名为 Messenger 的特征的东西。示例 15-20 显示了库代码。

Our library will only provide the functionality of tracking how close to the maximum a value is and what the messages should be at what times. Applications that use our library will be expected to provide the mechanism for sending the messages: The application could show the message to the user directly, send an email, send a text message, or do something else. The library doesn’t need to know that detail. All it needs is something that implements a trait we’ll provide, called Messenger. Listing 15-20 shows the library code.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-20/src/lib.rs}}

这段代码的一个重要部分是, Messenger 特征有一个名为 send 的方法,它接收对 self 的不可变引用和消息文本。这个特征是我们的模拟对象需要实现的接口,以便模拟对象可以像真实对象一样被使用。另一个重要部分是,我们想要测试 LimitTrackerset_value 方法的行为。我们可以改变为 value 参数传入的值,但 set_value 不返回任何内容供我们进行断言。我们想要做到的是,如果我们创建一个带有实现了 Messenger 特征的东西和特定 max 值的 LimitTracker ,那么当我们传入不同的 value 数字时,信使 (messenger) 会被告知发送适当的消息。

One important part of this code is that the Messenger trait has one method called send that takes an immutable reference to self and the text of the message. This trait is the interface our mock object needs to implement so that the mock can be used in the same way a real object is. The other important part is that we want to test the behavior of the set_value method on the LimitTracker. We can change what we pass in for the value parameter, but set_value doesn’t return anything for us to make assertions on. We want to be able to say that if we create a LimitTracker with something that implements the Messenger trait and a particular value for max, the messenger is told to send the appropriate messages when we pass different numbers for value.

我们需要一个模拟对象,当调用 send 时,它不发送电子邮件或短信,而只是记录被告知要发送的消息。我们可以创建一个模拟对象的新实例,创建一个使用该模拟对象的 LimitTracker ,调用 LimitTracker 上的 set_value 方法,然后检查模拟对象是否具有我们预期的消息。示例 15-21 展示了实现模拟对象以达到此目的的一次尝试,但借用检查器不允许这样做。

We need a mock object that, instead of sending an email or text message when we call send, will only keep track of the messages it’s told to send. We can create a new instance of the mock object, create a LimitTracker that uses the mock object, call the set_value method on LimitTracker, and then check that the mock object has the messages we expect. Listing 15-21 shows an attempt to implement a mock object to do just that, but the borrow checker won’t allow it.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-21/src/lib.rs:here}}

此测试代码定义了一个 MockMessenger 结构体,该结构体具有一个 sent_messages 字段,其包含一个 String 值的 Vec 以记录其被告知要发送的消息。我们还定义了一个关联函数 new ,以便方便地创建以空消息列表开始的新 MockMessenger 值。然后我们为 MockMessenger 实现 Messenger 特征,以便我们可以将 MockMessenger 交给 LimitTracker 。在 send 方法的定义中,我们将作为参数传入的消息存储在 MockMessengersent_messages 列表中。

This test code defines a MockMessenger struct that has a sent_messages field with a Vec of String values to keep track of the messages it’s told to send. We also define an associated function new to make it convenient to create new MockMessenger values that start with an empty list of messages. We then implement the Messenger trait for MockMessenger so that we can give a MockMessenger to a LimitTracker. In the definition of the send method, we take the message passed in as a parameter and store it in the MockMessenger list of sent_messages.

在测试中,我们正在测试当 LimitTracker 被告知将 value 设置为超过 max 值的 75% 时会发生什么。首先,我们创建一个新的 MockMessenger ,它将以一个空的消息列表开始。然后,我们创建一个新的 LimitTracker ,并给它一个指向新 MockMessenger 的引用和 100max 值。我们调用 LimitTracker 上的 set_value 方法,传入 80 的值,这超过了 100 的 75%。然后,我们断言 MockMessenger 正在记录的消息列表现在应该包含一条消息。

In the test, we’re testing what happens when the LimitTracker is told to set value to something that is more than 75 percent of the max value. First, we create a new MockMessenger, which will start with an empty list of messages. Then, we create a new LimitTracker and give it a reference to the new MockMessenger and a max value of 100. We call the set_value method on the LimitTracker with a value of 80, which is more than 75 percent of 100. Then, we assert that the list of messages that the MockMessenger is keeping track of should now have one message in it.

然而,这个测试有一个问题,如下所示:

However, there’s one problem with this test, as shown here:

{{#include ../listings/ch15-smart-pointers/listing-15-21/output.txt}}

我们无法修改 MockMessenger 以记录消息,因为 send 方法接收的是 self 的不可变引用。我们也不能采取错误文本中的建议,在 impl 方法和特征定义中都使用 &mut self 。我们不想仅仅为了测试而更改 Messenger 特征。相反,我们需要找到一种方法,让我们的测试代码在现有的设计下能够正确运行。

We can’t modify the MockMessenger to keep track of the messages, because the send method takes an immutable reference to self. We also can’t take the suggestion from the error text to use &mut self in both the impl method and the trait definition. We do not want to change the Messenger trait solely for the sake of testing. Instead, we need to find a way to make our test code work correctly with our existing design.

这就是内部可变性可以提供帮助的情况!我们将 sent_messages 存储在 RefCell<T> 中,然后 send 方法就能够修改 sent_messages 以存储我们见过的消息。示例 15-22 展示了它的样子。

This is a situation in which interior mutability can help! We’ll store the sent_messages within a RefCell<T>, and then the send method will be able to modify sent_messages to store the messages we’ve seen. Listing 15-22 shows what that looks like.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-22/src/lib.rs:here}}

sent_messages 字段现在的类型是 RefCell<Vec<String>> 而不是 Vec<String> 。在 new 函数中,我们在空向量周围创建一个新的 RefCell<Vec<String>> 实例。

The sent_messages field is now of type RefCell<Vec<String>> instead of Vec<String>. In the new function, we create a new RefCell<Vec<String>> instance around the empty vector.

对于 send 方法的实现,第一个参数仍然是 self 的不可变借用,这符合特征定义。我们对 self.sent_messages 中的 RefCell<Vec<String>> 调用 borrow_mut ,以获得对 RefCell<Vec<String>> 内部值(即向量)的可变引用。然后,我们可以对向量的可变引用调用 push ,以记录测试期间发送的消息。

For the implementation of the send method, the first parameter is still an immutable borrow of self, which matches the trait definition. We call borrow_mut on the RefCell<Vec<String>> in self.sent_messages to get a mutable reference to the value inside the RefCell<Vec<String>>, which is the vector. Then, we can call push on the mutable reference to the vector to keep track of the messages sent during the test.

我们需要做的最后一处更改是在断言中:为了查看内部向量中有多少项,我们对 RefCell<Vec<String>> 调用 borrow 以获得对向量的不可变引用。

The last change we have to make is in the assertion: To see how many items are in the inner vector, we call borrow on the RefCell<Vec<String>> to get an immutable reference to the vector.

既然你已经看到了如何使用 RefCell<T> ,让我们深入了解它的工作原理!

Now that you’ve seen how to use RefCell<T>, let’s dig into how it works!

在运行时跟踪借用 (Tracking Borrows at Runtime)

Tracking Borrows at Runtime

在创建不可变和可变引用时,我们分别使用 &&mut 语法。对于 RefCell<T> ,我们使用 borrowborrow_mut 方法,它们属于 RefCell<T> 的安全 API。 borrow 方法返回智能指针类型 Ref<T> ,而 borrow_mut 返回智能指针类型 RefMut<T> 。两种类型都实现了 Deref ,所以我们可以像处理普通引用一样处理它们。

When creating immutable and mutable references, we use the & and &mut syntax, respectively. With RefCell<T>, we use the borrow and borrow_mut methods, which are part of the safe API that belongs to RefCell<T>. The borrow method returns the smart pointer type Ref<T>, and borrow_mut returns the smart pointer type RefMut<T>. Both types implement Deref, so we can treat them like regular references.

RefCell<T> 跟踪当前有多少 Ref<T>RefMut<T> 智能指针处于活动状态。每次我们调用 borrowRefCell<T> 就会增加其活动不可变借用的计数。当一个 Ref<T> 值超出作用域时,不可变借用的计数就会减少 1。就像编译时借用规则一样, RefCell<T> 允许我们在任何时间点拥有许多不可变借用或一个可变借用。

The RefCell<T> keeps track of how many Ref<T> and RefMut<T> smart pointers are currently active. Every time we call borrow, the RefCell<T> increases its count of how many immutable borrows are active. When a Ref<T> value goes out of scope, the count of immutable borrows goes down by 1. Just like the compile-time borrowing rules, RefCell<T> lets us have many immutable borrows or one mutable borrow at any point in time.

如果我们尝试违反这些规则, RefCell<T> 的实现不会像引用那样产生编译器错误,而是在运行时引发恐慌。示例 15-23 显示了对示例 15-22 中 send 实现的修改。我们故意尝试在同一作用域内创建两个活动的可变借用,以说明 RefCell<T> 会在运行时阻止我们这样做。

If we try to violate these rules, rather than getting a compiler error as we would with references, the implementation of RefCell<T> will panic at runtime. Listing 15-23 shows a modification of the implementation of send in Listing 15-22. We’re deliberately trying to create two mutable borrows active for the same scope to illustrate that RefCell<T> prevents us from doing this at runtime.

{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-23/src/lib.rs:here}}

我们为 borrow_mut 返回的 RefMut<T> 智能指针创建了一个变量 one_borrow 。然后,我们在变量 two_borrow 中以相同的方式创建了另一个可变借用。这就在同一作用域内创建了两个可变引用,这是不允许的。当我们运行库的测试时,示例 15-23 中的代码将通过编译且没有任何错误,但测试会失败:

We create a variable one_borrow for the RefMut<T> smart pointer returned from borrow_mut. Then, we create another mutable borrow in the same way in the variable two_borrow. This makes two mutable references in the same scope, which isn’t allowed. When we run the tests for our library, the code in Listing 15-23 will compile without any errors, but the test will fail:

{{#include ../listings/ch15-smart-pointers/listing-15-23/output.txt}}

注意,代码发生了恐慌,消息为 already borrowed: BorrowMutError 。这就是 RefCell<T> 在运行时处理违反借用规则的方式。

Notice that the code panicked with the message already borrowed: BorrowMutError. This is how RefCell<T> handles violations of the borrowing rules at runtime.

选择在运行时而不是编译时捕获借用错误,正如我们在这里所做的,意味着你可能会在开发过程的后期(甚至可能直到代码部署到生产环境之后)才发现代码中的错误。此外,由于在运行时跟踪借用,你的代码还会承担一小部分运行时性能开销。然而,使用 RefCell<T> 使得编写一个能够在仅允许不可变值的上下文中使用时修改自身的模拟对象成为可能。尽管有这些权衡,你仍然可以使用 RefCell<T> 来获得比普通引用更多的功能。

Choosing to catch borrowing errors at runtime rather than compile time, as we’ve done here, means you’d potentially be finding mistakes in your code later in the development process: possibly not until your code was deployed to production. Also, your code would incur a small runtime performance penalty as a result of keeping track of the borrows at runtime rather than compile time. However, using RefCell<T> makes it possible to write a mock object that can modify itself to keep track of the messages it has seen while you’re using it in a context where only immutable values are allowed. You can use RefCell<T> despite its trade-offs to get more functionality than regular references provide.

允许可变数据的多重所有权 (Allowing Multiple Owners of Mutable Data)

使用 RefCell<T> 的一种常见方法是将其与 Rc<T> 结合使用。回想一下, Rc<T> 让你能够为一个数据拥有多个所有者,但它仅提供对该数据的不可变访问。如果你拥有一个持有 RefCell<T>Rc<T> ,你就可以获得一个既可以拥有多个所有者“又”可以被修改的值!

A common way to use RefCell<T> is in combination with Rc<T>. Recall that Rc<T> lets you have multiple owners of some data, but it only gives immutable access to that data. If you have an Rc<T> that holds a RefCell<T>, you can get a value that can have multiple owners and that you can mutate!

例如,回想示例 15-18 中的 cons list 示例,我们在那里使用 Rc<T> 允许多个列表共享另一个列表的所有权。因为 Rc<T> 仅持有不可变值,所以一旦创建了列表,我们就无法更改列表中的任何值。让我们加入 RefCell<T> 以获得更改列表中值的能力。示例 15-24 显示了通过在 Cons 定义中使用 RefCell<T> ,我们可以修改存储在所有列表中的值。

For example, recall the cons list example in Listing 15-18 where we used Rc<T> to allow multiple lists to share ownership of another list. Because Rc<T> holds only immutable values, we can’t change any of the values in the list once we’ve created them. Let’s add in RefCell<T> for its ability to change the values in the lists. Listing 15-24 shows that by using a RefCell<T> in the Cons definition, we can modify the value stored in all the lists.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch15-smart-pointers/listing-15-24/src/main.rs}}
}

我们创建了一个 Rc<RefCell<i32>> 实例的值并将其存储在名为 value 的变量中,以便稍后直接访问它。然后,我们在 a 中创建了一个具有持有 valueCons 变体的 List 。我们需要克隆 value ,以便 avalue 都拥有内部值 5 的所有权,而不是将所有权从 value 转移到 a ,或者让 a 借用自 value

We create a value that is an instance of Rc<RefCell<i32>> and store it in a variable named value so that we can access it directly later. Then, we create a List in a with a Cons variant that holds value. We need to clone value so that both a and value have ownership of the inner 5 value rather than transferring ownership from value to a or having a borrow from value.

我们将列表 a 包裹在 Rc<T> 中,这样当我们创建列表 bc 时,它们都可以引用 a ,这就是我们在示例 15-18 中所做的。

We wrap the list a in an Rc<T> so that when we create lists b and c, they can both refer to a, which is what we did in Listing 15-18.

在我们创建了 abc 中的列表后,我们想给 value 中的值加 10。我们通过在 value 上调用 borrow_mut 来实现这一点,它使用了我们在第 5 章-> 运算符在哪?”中讨论过的自动解引用功能,将 Rc<T> 解引用为内部的 RefCell<T> 值。 borrow_mut 方法返回一个 RefMut<T> 智能指针,我们对其使用解引用运算符并更改内部值。

After we’ve created the lists in a, b, and c, we want to add 10 to the value in value. We do this by calling borrow_mut on value, which uses the automatic dereferencing feature we discussed in “Where’s the -> Operator?” in Chapter 5 to dereference the Rc<T> to the inner RefCell<T> value. The borrow_mut method returns a RefMut<T> smart pointer, and we use the dereference operator on it and change the inner value.

当我们打印 abc 时,我们可以看到它们都具有修改后的值 15 而不是 5

{{#include ../listings/ch15-smart-pointers/listing-15-24/output.txt}}

这种技术非常巧妙!通过使用 RefCell<T> ,我们得到了一个外表不可变的 List 值。但我们可以使用 RefCell<T> 上提供访问其内部可变性的方法,以便在需要时修改我们的数据。借用规则的运行时检查保护我们免受数据竞争的影响,有时为了这种数据结构的灵活性,牺牲一点速度是值得的。请注意, RefCell<T> 不适用于多线程代码! Mutex<T>RefCell<T> 的线程安全版本,我们将在第 16 章讨论 Mutex<T>

This technique is pretty neat! By using RefCell<T>, we have an outwardly immutable List value. But we can use the methods on RefCell<T> that provide access to its interior mutability so that we can modify our data when we need to. The runtime checks of the borrowing rules protect us from data races, and it’s sometimes worth trading a bit of speed for this flexibility in our data structures. Note that RefCell<T> does not work for multithreaded code! Mutex<T> is the thread-safe version of RefCell<T>, and we’ll discuss Mutex<T> in Chapter 16.