1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
// 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
}
|