From 436bcad0e16bd484e01abf46355568dc6290ad09 Mon Sep 17 00:00:00 2001 From: vinchent Date: Sat, 21 Sep 2024 19:48:58 +0200 Subject: [PATCH] counter: Use a constructor --- counter/counter.go | 4 ++++ counter/counter_test.go | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/counter/counter.go b/counter/counter.go index 73cf51e..716f227 100644 --- a/counter/counter.go +++ b/counter/counter.go @@ -7,6 +7,10 @@ type Counter struct { mutex sync.Mutex } +func NewCounter() *Counter { + return &Counter{} +} + func (c *Counter) Inc() { c.mutex.Lock() defer c.mutex.Unlock() diff --git a/counter/counter_test.go b/counter/counter_test.go index 6349684..edabe61 100644 --- a/counter/counter_test.go +++ b/counter/counter_test.go @@ -16,18 +16,18 @@ func assertCounter(t testing.TB, got *Counter, want int) { func TestCounter(t *testing.T) { t.Run("incrementing the counter 3 times leaves it at 3", func(t *testing.T) { - counter := Counter{} + counter := NewCounter() counter.Inc() counter.Inc() counter.Inc() - assertCounter(t, &counter, 3) + assertCounter(t, counter, 3) }) t.Run("it runs safely concurrently", func(t *testing.T) { wantedCount := 1000 - counter := Counter{} + counter := NewCounter() var wg sync.WaitGroup wg.Add(wantedCount) @@ -39,6 +39,6 @@ func TestCounter(t *testing.T) { }() } wg.Wait() - assertCounter(t, &counter, wantedCount) + assertCounter(t, counter, wantedCount) }) }