Skip to content

Instantly share code, notes, and snippets.

@1xtr
Created January 26, 2025 23:39
Show Gist options
  • Save 1xtr/c52b9f53c42b7b4684178d670d070147 to your computer and use it in GitHub Desktop.
Save 1xtr/c52b9f53c42b7b4684178d670d070147 to your computer and use it in GitHub Desktop.
Golang alternative of JavaScript Set
package models
// Set is a simple set implementation using a map.
type Set[T comparable] map[T]struct{}
// NewSet creates and returns a new Set.
func NewSet[T comparable]() Set[T] {
return make(Set[T])
}
// Add adds a value to the set.
func (s Set[T]) Add(val T) {
s[val] = struct{}{}
}
// Contains checks if the set contains a value.
func (s Set[T]) Contains(val T) bool {
_, ok := s[val]
return ok
}
// ToSlice returns the set's elements as a slice.
func (s Set[T]) ToSlice() []T {
keys := make([]T, 0, len(s))
for k := range s {
keys = append(keys, k)
}
return keys
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment