O'Reilly logo

Mastering Rust by Vesa Kaihlavirta

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reference collected memory: Rc<T> and Arc<T>

Reference counting is a simple form of garbage collection. The basic flow of events with Rc is as follows:

  • Every time somebody takes a new reference, we increment an internal counter
  • Every time somebody drops a reference, we decrement it
  • When the internal counter hits zero, nobody refers to the object anymore, so it can be dropped

Using variables in reference counted containers gives us more flexibility in the implementation: we can hand out references to a value without having to keep exact track of when the references go out of scope.

Rc<T> is mostly used via two methods:

  • The static method Rc::new makes a new reference collected container (you should start recognizing a pattern already!)

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required