// Package generic provides common generic utility functions and types. // // It includes zero value helpers, pointer helpers, iteration helpers for map-like sequences, // and a simple generic Set implementation. package generic import ( "iter" "maps" ) // Package generic provides common generic utility functions and types. // // It includes zero value helpers, pointer helpers, iteration helpers for map-like sequences, // and a simple generic Set implementation. func Zero[T any]() T { var v T return v } // IsZero reports whether the given value is the zero value of its type. // // T must be comparable (support == operator). // // Example: // // generic.IsZero(0) // true // generic.IsZero("a") // false func IsZero[T comparable](v T) bool { return v == Zero[T]() } // Ptr returns a pointer to the given value. // // This is a concise helper to get the address of a value inline. // // Example: // // p := generic.Ptr(42) // *int with value 42 func Ptr[T any](v T) *T { return &v } // Keys returns an iterator (Seq) over the keys of the input map-like sequence. // // Utilizes iter.Seq2[K,V] as input and yields keys K. // // Usage example (assuming iter.Seq is a func type yielding values): // // forKeys := generic.Keys(yourMapSeq) // forKeys(func(k K) bool { // fmt.Println(k) // return true // }) func Keys[K comparable, V any](m iter.Seq2[K, V]) iter.Seq[K] { return func(yield func(K) bool) { for k := range m { if !yield(k) { return } } } } // Value returns an iterator over the values of the input map-like sequence. // // Usage is analogous to Keys() but yields values of type V. func Value[K comparable, V any](m iter.Seq2[K, V]) iter.Seq[V] { return func(yield func(V) bool) { for _, v := range m { if !yield(v) { return } } } } // Set represents a generic set of comparable items. // // It is a thin wrapper around a map[T]struct{} for set semantics. type Set[T comparable] map[T]struct{} func NewSet[T comparable]() Set[T] { return make(Set[T]) } // All returns an iterator (Seq) over all elements in the Set. func (s Set[T]) All() iter.Seq[T] { return maps.Keys(s) } // Add inserts the value v into the Set. func (s Set[T]) Add(v T) { s[v] = struct{}{} } // Del removes the value v from the Set. func (s Set[T]) Del(v T) { delete(s, v) } // Has reports whether the value v is present in the Set. func (s Set[T]) Has(v T) bool { _, ok := s[v] return ok }