In Rust, methods and associated functions are both defined using impl blocks. While they are similar in some ways, they serve different purposes:
-
Associated Functions:
- Defined without a
selfparameter. - Typically used as constructors or utility functions.
- Called using the struct's name, e.g.,
StructName::function_name().
- Defined without a
-
Methods:
- Defined with a
selfparameter (&self,&mut self, orself). - Operate on an instance of the struct.
- Called on a struct instance using the dot syntax, e.g.,
instance.method_name().
- Defined with a
In the previous challenge, the Logger::log_message was an associated function because it didn't take self as a parameter. In this challenge, you will learn how to create methods that operate on struct instances.
Your Task
Define a struct Counter that represents a simple counter. Implement methods on this struct to increment, decrement, and get the current count. This will help you understand how to define and use methods that operate on a struct instance.
Requirements
-
Define a struct
Counterwith a single fieldcountof typei32. -
Define a
newassociated function that acts as a constructor and initializes thecountfield to 0. -
Implement the following methods for
Counter:increment: Increments the counter by 1.decrement: Decrements the counter by 1.get_count: Returns the current count.
-
Ensure these methods use the correct
selfparameter type (&selfor&mut self) based on their behavior. -
Make the
countfield private and provide a public constructorCounter::newthat initializes the count to 0.
Example Test
let mut counter = Counter::new();counter.increment();counter.increment();assert_eq!(counter.get_count(), 2);counter.decrement();assert_eq!(counter.get_count(), 1);
Hints
If you're stuck, you can check out these hints:
<details> <summary>Click here to reveal hints</summary>- Fort he
incrementanddecrementmethods, use&mut selfas the parameter type. - Use
self.count += 1to modify the counter in theincrementmethod. - Use
self.count -= 1to modify the counter in thedecrementmethod. - For
get_count, use&selfand return the value ofself.count.
// 1. Define the structpub struct Counter// 2. Implement the associated function and methods// Example use casepub fn main() {let mut counter = Counter::new();counter.increment();assert_eq!(counter.get_count(), 1);counter.increment();counter.increment();assert_eq!(counter.get_count(), 3);counter.decrement();assert_eq!(counter.get_count(), 2);counter.decrement();counter.decrement();assert_eq!(counter.get_count(), 0);}