Skip to main content

2 docs tagged with "cycles"

View all tags

Reference Cycles and How to Prevent Them

The Rc and RefCell patterns are incredibly powerful, but they come with a potential danger: reference cycles. A reference cycle is a situation where items reference each other in a loop, causing their reference counts to never drop to zero. This is a form of memory leak, and while Rust's ownership system prevents most memory safety issues, this is one you must handle carefully yourself. In this article, we'll learn how to create a reference cycle and how to prevent it using weak references.

Weak<T> to Create Non-Owning References

In the last article, we saw how Rc can create reference cycles, leading to memory leaks. To solve this, Rust provides a companion smart pointer:Weak. A Weak is a non-owning reference that allows you to refer to data owned by an Rc without contributing to its strong reference count. This is the primary tool for breaking reference cycles and creating temporary, safe references to data.