diff --git a/Collection.go b/Collection.go index ba7a623..c7fcf1c 100644 --- a/Collection.go +++ b/Collection.go @@ -2,41 +2,39 @@ package ocean import "sync" -type Collection interface { - Get(key string) (value any, ok bool) +type Collection[T any] interface { + Get(key string) (value T, ok bool) } // collection is a hash map of homogeneous data. -type collection struct { +type collection[T any] struct { data sync.Map name string } -// Force interface implementation -var _ Collection = (*collection)(nil) - // NewCollection creates a new collection with the given name. -func NewCollection(name string) *collection { - return &collection{name: name} +func NewCollection[T any](name string) *collection[T] { + return &collection[T]{name: name} } // Get returns the value for the given key. -func (c *collection) Get(key string) (value any, ok bool) { - return c.data.Load(key) +func (c *collection[T]) Get(key string) (T, bool) { + value, exists := c.data.Load(key) + return value.(T), exists } // Set sets the value for the given key. -func (c *collection) Set(key string, value any) { +func (c *collection[T]) Set(key string, value T) { c.data.Store(key, value) } // Delete deletes a key from the collection. -func (c *collection) Delete(key string) { +func (c *collection[T]) Delete(key string) { c.data.Delete(key) } // Exists returns whether or not the key exists. -func (c *collection) Exists(key string) bool { +func (c *collection[T]) Exists(key string) bool { _, exists := c.data.Load(key) return exists } diff --git a/Collection_test.go b/Collection_test.go index 1a83c30..8cf4ecc 100644 --- a/Collection_test.go +++ b/Collection_test.go @@ -8,7 +8,7 @@ import ( ) func TestNewCollection(t *testing.T) { - users := ocean.NewCollection("User") + users := ocean.NewCollection[string]("User") assert.False(t, users.Exists("Hello")) assert.False(t, users.Exists("World"))