In Rust, methods and associated functions are both defined using impl
blocks. While they are similar in some ways, they serve different purposes:
self
parameter.StructName::function_name()
.self
parameter (&self
, &mut self
, or self
).instance.method_name()
.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.
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.
Define a struct Counter
with a single field count
of type i32
.
Define a new
associated function that acts as a constructor and initializes the count
field 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 self
parameter type (&self
or &mut self
) based on their behavior.
Make the count
field private and provide a public constructor Counter::new
that initializes the count to 0.
If you're stuck, you can check out these hints:
increment
and decrement
methods, use &mut self
as the parameter type.self.count += 1
to modify the counter in the increment
method.self.count -= 1
to modify the counter in the decrement
method.get_count
, use &self
and return the value of self.count
.