Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The RefCell pointer type implements single ownership like Box, but enforces borrowing rules only at runtime.

By default the following borrowing rules are enforced at compile time:

The implementation of RefCell, on the other hand, enforces these same rules at runtime. This means that:

Table 1:Some methods of RefCell

Method

Description

new(x)

Constructs a new RefCell object.

borrow()

Returns an immutable reference Ref to the wrapped value. Multiple immutable borrows can exist at the same time. Panics if a mutable borrow exists.

borrow_mut()

Returns a mutable reference RefMut to the wrapped value. Panics if the value is already borrowed.

replace(v)

Replaces the wrapped value with v. Panics if the value is already borrowed.

swap(other)

Swaps the wrapped value with the one from other.

take()

Extracts the wrapped value, leaving the default value in its place. Panics if the value is already borrowed.

try_borrow()

Tries to immutably borrow the wrapped value. Returns an error if it fails.

try_borrow_mut()

Tries to mutably borrow the wrapped value. Returns an error if it fails.

As an example we are going to create a Fib structure that computes numbers from the Fibonacci sequence, but uses a cache to speed up computing of the current request and future requests. As the computing method get() should not modify anything from the perspective of the Fib’s caller, it takes an immutable self instance. But since it possibly needs to modify the cache, we will use a RefCell for the cache. This caching technique for a function is called Memoization.

Here is the code of our Fib structure, we use a vector of 64-bit integers for the cache:

The constructor initializes the cache with an empty vector:

The get() method computes a Fibonacci value, checking if the value is already computed and stored into the cache, or computing the value and storing it into the cache:

We create a new instance of Fib:

Here is the computing of the 50th number of the Fibonacci sequence:

12586269025

see solution