Go Pointer Methods: Modifying Struct Values
This challenge focuses on understanding and implementing pointer receivers for methods in Go. Pointer receivers allow methods to modify the state of the struct they are called on, which is a fundamental concept for object-oriented-like programming in Go.
Problem Description
You are tasked with creating a Counter struct in Go. This struct should have a single integer field, value, initialized to zero. You need to implement two methods for the Counter struct:
Increment(): This method should increase thevalueof theCounterby 1.Decrement(): This method should decrease thevalueof theCounterby 1.
Crucially, these methods must modify the original Counter struct instance. This means they must use pointer receivers.
Key Requirements
- Define a
Counterstruct with an integer field namedvalue. - Implement an
Increment()method that takes a pointer receiver (*Counter) and increases itsvalueby 1. - Implement a
Decrement()method that takes a pointer receiver (*Counter) and decreases itsvalueby 1. - The
valuefield should be accessible (e.g., using a getter method or by making it public if appropriate for the challenge context). For this challenge, we'll assume direct access tovaluefor verification.
Expected Behavior
When Increment() is called on a Counter instance, its value should increase. When Decrement() is called, its value should decrease.
Edge Cases
- What happens when
Decrement()is called whenvalueis already zero? The value should simply become -1. - Consider the behavior with multiple method calls chained together.
Examples
Example 1:
Input:
counter := Counter{}
counter.Increment()
counter.Increment()
counter.Decrement()
Output:
1
Explanation:
The counter starts with value = 0.
Increment() is called twice: value becomes 1, then 2.
Decrement() is called once: value becomes 1.
Example 2:
Input:
counter := Counter{}
counter.Decrement()
counter.Decrement()
counter.Increment()
Output:
-1
Explanation:
The counter starts with value = 0.
Decrement() is called twice: value becomes -1, then -2.
Increment() is called once: value becomes -1.
Example 3:
Input:
counter := Counter{value: 10}
counter.Increment()
counter.Increment()
counter.Decrement()
counter.Decrement()
counter.Decrement()
Output:
9
Explanation:
The counter starts with value = 10.
Two Increment() calls result in value = 12.
Three Decrement() calls result in value = 9.
Constraints
- The
valuefield must be anint. - The
IncrementandDecrementmethods must use pointer receivers (*Counter). - No external libraries or packages are required.
Notes
Remember that when you pass a struct value to a function or a method with a value receiver, a copy of the struct is made. Modifications to that copy will not affect the original struct. Pointer receivers, on the other hand, operate directly on the original struct instance. This is why pointer receivers are essential for methods that need to change the state of the object they are invoked on.