Sobes.tech
Junior

How can a set be implemented in Go?

sobes.tech AI

Answer from AI

In Go, there is no built-in 'set' data type. It can be implemented using map.

// Implementation of a string set
type Set map[string]struct{}

// Add an element
func (s Set) Add(item string) {
	s[item] = struct{}{} // Using struct{} to avoid extra memory usage
}

// Remove an element
func (s Set) Remove(item string) {
	delete(s, item)
}

// Check if an element exists
func (s Set) Contains(item string) bool {
	_, ok := s[item]
	return ok
}

// Get all elements (unordered)
func (s Set) ToSlice() []string {
	slice := make([]string, 0, len(s))
	for item := range s {
		slice = append(slice, item)
	}
	return slice
}