SoFunction
Updated on 2025-03-01

Golang implementation supports multiple types of sets

Write in front

Today, the project needs to use string type set. I think it is needed in many places in the project, and they all use it.map[string]boolImplemented, since set is used to deduplicate so many places, why not write a set? Moreover, go now supports generics, why not write a set that supports multiple types? Do it as soon as you say

Code

    package set
    var (
    	ElemValue = struct{}{}
    )
    type SetType interface {
    	int | int32 | int64 | string | float32 | float64
    }
    // Set[T SetType]. Collection, thread is not safe    type Set[T SetType] interface {
    	Add(T)
    	Remove(T)
    	Contains(T) bool
    	Empty() bool
    	Values() []T
    }
    type set[T SetType] struct {
    	m map[T]struct{}
    }
    func NewSet[T SetType](ss ...T) Set[T] {
    	newSet := set[T]{
    		m: make(map[T]struct{}, len(ss)),
    	}
    	for _, s := range ss {
    		(s)
    	}
    	return &newSet
    }
    func (s *set[T]) Add(elem T) {
    	[elem] = ElemValue
    }
    func (s *set[T]) Remove(elem T) {
    	delete(, elem)
    }
    func (s *set[T]) Contains(elem T) bool {
    	_, ok := [elem]
    	return ok
    }
    func (s *set[T]) Empty() bool {
    	empty := true
    	for _, _ = range  {
    		empty = false
    		break
    	}
    	return empty
    }
    func (s *set[T]) Values() []T {
    	ss := make([]T, 0)
    	for k, _ := range  {
    		ss = append(ss, k)
    	}
    	return ss
    }

After writing it, I found that there were only more than 60 lines of code, which is very simple, and the value is used.struct{}{}, does not occupy any memory

Single test

    package set_test
    import (
    	"set"
    	"testing"
    	"/stretchr/testify/assert"
    )
    func TestStringSet(t *) {
    	newSet := [string]("a", "b")
    	(t, ())
    	("c")
    	("a")
    	(t, ("a"))
    	(t, ("c"))
    	("c")
    	result := ()
    	(t, "b", result[0])
    }
    func TestInt64Set(t *) {
    	newSet := [int64](1, 2)
    	(t, ())
    	(3)
    	(1)
    	(t, (1))
    	(t, (3))
    	(3)
    	result := ()
    	(t, int64(2), result[0])
    }

Wheel creation thoughts

I haven't used go generics before. Today I wrote this set and experienced the generics. They are really useful. I like to build wheels and support making wheels. Only in this way can you improve yourself and learn together

This is the end of this article about Golang implementing support for multiple types of sets. For more related content on Golang implementation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!