From d27dc4d69bda7e98c33ad99955972f6e163b608c Mon Sep 17 00:00:00 2001 From: Kevin Joiner <10265309+KevinJoiner@users.noreply.github.com> Date: Mon, 19 Aug 2024 09:29:04 -0400 Subject: [PATCH] give sets a usable zero value --- set/set.go | 11 +++++++++-- set/set_test.go | 11 +++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/set/set.go b/set/set.go index d66b30d..d43e168 100644 --- a/set/set.go +++ b/set/set.go @@ -13,12 +13,19 @@ func New[A comparable](as ...A) Set[A] { } // Add adds an element to the set. -func (s Set[A]) Add(a A) { - s[a] = struct{}{} +func (s *Set[A]) Add(a A) { + if *s == nil { + *s = New(a) + return + } + (*s)[a] = struct{}{} } // Contains checks if an element is in the set. func (s Set[A]) Contains(a A) bool { + if s == nil { + return false + } _, ok := s[a] return ok } diff --git a/set/set_test.go b/set/set_test.go index 56ca99d..0ff183c 100644 --- a/set/set_test.go +++ b/set/set_test.go @@ -21,4 +21,15 @@ func TestSet(t *testing.T) { if s.Contains("xpp") { t.Error("set contains xpp but this was never added") } + + var s2 Set[int] + s2.Add(2) + if !s2.Contains(2) { + t.Error("expected set to contain 2 but it did not") + } + + var s3 Set[uint32] + if s3.Contains(2) { + t.Error("expected set to not contain 2 but it did") + } }