Challenge: Rust Advanced Concepts
Test your understanding of what you learned in this chapter by tackling a problem about smart pointers.
We'll cover the following
Challenge
You've been assigned the task of implementing a simple counter system using smart pointers in Rust. Your objective is to create a Counter
struct that utilizes a smart pointer (either Rc
or Arc
) to keep track of the number of times an instance has been cloned. Furthermore, you are required to implement a method that allows users to retrieve the current count.
Task
Create a simple counter using smart pointers in Rust. Implement a Counter
struct that internally uses a smart pointer (e.g., Rc
or Arc
) to keep track of the number of times an instance has been cloned. Additionally, implement a method to retrieve the current count. Make sure to follow the requirements given below:
Define a struct called
Counter
with an internal smart pointer to keep track of the count.Implement a
new
method that initializes a newCounter
with an initial count of zero.Implement a
clone_and_increment
method that clonesCounter
and increments the count.Implement a
get_count
method that returns the current count.
Try it yourself
The skeleton code to test out your implementations for the reference counter is given below.
Get hands-on with 1400+ tech skills courses.