How to Clone Arc in Rust
- Shared Ownership in Rust
-
Effect of Cloning the
Arc
in Rust -
Effect on Memory Using
Rc
in Rust -
clone()
theRc
in Rust -
Difference Between
Arc<T>
andRc<T>
in Rust
This article is about the Atomically Reference Counted (Arc)
, a proxy that handles one object (of type T
) and allows for shared ownership. We will also learn that using the clone()
function creates a new owned handle, which can be moved to a new thread.
In addition, we will learn about shared ownership with the help of an example.
Shared Ownership in Rust
Shared ownership refers to the ownership of a single object by multiple names. For example, a dog you bought for your family.
You cannot assign one clear owner as all the family members share ownership of that dog. We must realize that if one of the family members dies, the dog will not die with them.
On the other hand, the dog will die if all family members die. The rationale goes like this: everyone owns something, and the last one standing cleans it up.
Likely, using conventional Rust techniques alone won’t be enough to describe this form of shared ownership. For example, you must always designate one owner to the dog, and others can merely refer to the dog.
Rc
and Arc
in Rust allow for shared ownership.
Effect of Cloning the Arc
in Rust
The type Arc<T>
represents the ownership of a type T
value in a shared medium allocated in the leap. A new Arc
instance is formed when a reference count increases, connecting to the same allocation on the heap as the originating Arc
.
Effect on Memory Using Rc
in Rust
let nil = Rc::new(Dog { legs: 4 });
In the memory, the dog lives on the heap with a count of 1
(the counter is set to 1
). So the counter is aware of the number of owners that the object data has in the current situation.
And 1
is correct as nil
is the one who owns the dog at the moment.
clone()
the Rc
in Rust
let esh = nil.clone();
let kat = nil.clone();
As a result of this code, the dog exists only once in memory. However, the reference count increases to 3
, which is logical as the dog has three owners.
These three owners reference the memory block on the heap. This way, Rust book calls owned handle: each owner owns the underlying object.
We need to know that clone()
on an Arc<T>
will not clone T
but create another owned handle. It is just a pointer that behaves as if it holds the underlying object.
Difference Between Arc<T>
and Rc<T>
in Rust
Multiple threads can increment and decrease the counter in an atomic manner using Arc
without issue. As a result, Arc
isn’t restricted to thread boundaries.
However, Arc
is not meant to provide simultaneous mutable access from multiple owners. So, Rc<T>
is for multiple ownership, whereas Arc<T>
is for multiple ownership beyond thread boundary.
Rc<T>
allows us to have several owning pointers to the same data, and the data is freed after all pointers have been released.