Home
Blog
When to Use Rc and Arc in Rust
Updated
Dot Net Perls

When to Use Rc and Arc in Rust

Suppose you (as a Rust developer) have built up a struct instance with some data—like the text of a file. Let's call this struct FileData. And you want to access this data in various functions in the program. Rc or Arc can be used for this purpose.

The program has a couple other structs that are used throughout—let's call them Info and InfoTwo. Many functions in the program have arguments of types Info and InfoTwo. We can put an Rc or Arc containing the FileData on these structs.

Though it is accessible from two structs (Info and InfoTwo) the FileData struct is only resident in memory once. It was never copied—just an Rc or Arc was copied, and this involves just an integer increment, and a small number of bytes. This is called reference counting.

If Info and InfoTwo are passed to different threads, we should place them in Arc—otherwise, we can just use Rc. In my experience, Arc is preferred as most Rust developers want to use threads, and Arc will work correctly on a single thread as well.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen