Generic Set Type Backed By A Map
Define Set[T comparable] over map[T]struct{} with Add, Has, Len, and a non-mutating Union so membership helpers stay type-safe.
Code
package main
import "fmt"
// Set[T comparable] 用 map[T]struct{} 存成员,struct{} 值零字节
type Set[T comparable] struct {
members map[T]struct{}
}
func NewSet[T comparable](items ...T) *Set[T] {
s := &Set[T]{members: make(map[T]struct{})}
for _, v := range items {
s.members[v] = struct{}{}
}
return s
}
func (s *Set[T]) Add(v T) {
s.members[v] = struct{}{}
}
func (s *Set[T]) Has(v T) bool {
_, ok := s.members[v]
return ok
}
func (s *Set[T]) Len() int {
return len(s.members)
}
// Union 返回新集合,不改动两个接收者
func (s *Set[T]) Union(other *Set[T]) *Set[T] {
out := NewSet[T]()
for v := range s.members {
out.members[v] = struct{}{}
}
for v := range other.members {
out.members[v] = struct{}{}
}
return out
}
func main() {
core := NewSet("read", "write")
ops := NewSet("write", "delete")
fmt.Println("core has read:", core.Has("read"))
fmt.Println("core has delete:", core.Has("delete"))
merged := core.Union(ops)
fmt.Println("union len:", merged.Len(), "core len:", core.Len())
}How the snippet works
The snippet is organized around the functions Add, Has, Len and Union.
The one repetition in this snippet is the loop for _, v := range items.
Watch out for
- Zero third-party dependencies — the runtime provides every API used here.
Putting it to use
Entry signature: func (s *Set[T]) Add(v T)
Watch the output for labels — core has read:, core has delete:, union len: — when the file runs.
Running the file executes main, which drives Has, Union and Len in order.
Core lines
func NewSet[T comparable](items ...T) *Set[T] {
s := &Set[T]{members: make(map[T]struct{})}
for _, v := range items {
s.members[v] = struct{}{}
}
return s
}
func (s *Set[T]) Union(other *Set[T]) *Set[T] {
out := NewSet[T]()
for v := range s.members {
out.members[v] = struct{}{}
}
for v := range other.members {
out.members[v] = struct{}{}
}
return out
}
func (s *Set[T]) Has(v T) bool {
_, ok := s.members[v]
return ok
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Generic Set Type Backed By A Map print when run?
- Execute the whole file; each printed line is prefixed with a label like `core has read:`, `core has delete:`, `union len:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.