0:00
/
0:00
Transcript

Weak References in Rust

Refer to objects without keeping them alive

Code on GitHub: https://github.com/caveofprogramming/rust/

A weak reference in Rust is a kind of smart pointer that can be used to obtain an actual (“strong”) reference to an object, but doesn’t itself keep the object alive. Memory used by the object is reclaimed as soon as there are no further strong references to the object, regardless of whether there are weak references referring to it.

First we’ll create a normal strong reference using Rc, the reference counter.

This prints:

We have one “normal” (strong) reference to the integer value, and no weak references. As long as the strong reference exists, the value will not get dropped.

We can create a weak reference by using the downgrade() method of the Rc object.

The type of the object returned in this case will be Weak<i32>. If you need to import Weak, it’s std::rc::Weak.

Now we have one strong reference and one weak reference. The weak reference will not by itself keep the object alive.

To make use of a weak reference, we use the upgrade() method of Weak, which returns an Option.

If the object has been dropped, we get back None. Otherwise, we get Some, wrapping a strong reference to the object.

The scope of the strong reference obtained is just the if let block here.

If we add another print after this, outside the block, we see that we’ve got back to 1 strong reference and 1 weak reference.

A possible use case for this is a tree structure where each node has strong references to its children, keeping them alive, and a weak reference to its parent, which doesn’t keep the parent alive and doesn’t create recursion if we try to print the tree.

Discussion about this video

User's avatar