collections API

collections

package

API reference for the collections package.

S
struct

Set

Set is a generic thread-safe set.

pkg/collections/set.go:12-15
type Set struct

Example

s := collections.NewSet[string]()
s.Add("a", "b")
if s.Has("a") { ... }

Fields

Name Type Description
items map[T]struct{}
mu sync.RWMutex
F
function

NewSet

NewSet creates a new empty Set.

Returns

*Set[T]
pkg/collections/set.go:18-22
func NewSet[T comparable]() *Set[T]

{
	return &Set[T]{
		items: make(map[T]struct{}),
	}
}
F
function

TestSet

Parameters

pkg/collections/set_test.go:7-33
func TestSet(t *testing.T)

{
	s := NewSet[int]()

	s.Add(1, 2, 3)
	if s.Len() != 3 {
		t.Errorf("Len: got %d, want 3", s.Len())
	}

	if !s.Has(2) {
		t.Error("Has 2: should be true")
	}

	s.Remove(2)
	if s.Has(2) {
		t.Error("Has 2: should be false after removal")
	}

	items := s.Items()
	if len(items) != 2 {
		t.Errorf("Items: got %d, want 2", len(items))
	}

	s.Clear()
	if s.Len() != 0 {
		t.Error("Clear should empty the set")
	}
}