skip to content
Alvin Lucillo

Implementing generic map type

/ 1 min read

Below we have implemented a Set that is a generic map type. Set only keeps unique set of keys, that is why we only set struct{}{} for every key.

Set is of type map[T]struct{} where T is a comparable constraint.

type Set[T comparable] map[T]struct{}

func (s Set[T]) Add(v T) {
	s[v] = struct{}{}
}

func (s Set[T]) Exists(v T) bool {
	_, ok := s[v]
	return ok
}

func (s Set[T]) Remove(v T) {
	delete(s, v)
}

type V struct {
	value int
}

func main() {
	s1 := Set[string]{}
	s1.Add("a")
	fmt.Println(s1.Exists("a")) // true
	s1.Remove("a")
	fmt.Println(s1.Exists("a")) // false

	s2 := Set[[2]string]{}
	s2.Add([2]string{"a", "b"})
	fmt.Println(s2.Exists([2]string{"a", "c"})) // false

	s3 := Set[V]{}
	s3.Add(V{value: 2})
	fmt.Println(s3.Exists(V{value: 2})) // true
}