Sobes.tech
Junior — Middle

Is it possible to create a structure or data type similar to a set in Go language?

sobes.tech AI

Answer from AI

In Go, there is no built-in 'set' type, but it can be implemented using a map with keys of the desired type and values of type struct{} or bool. Using struct{} saves memory because an empty struct occupies no space.

Example of implementing a string set:

// Create a set of strings
set := make(map[string]struct{})

// Add an element
set["apple"] = struct{}{}

// Check for an element
if _, exists := set["apple"]; exists {
    fmt.Println("Element exists in the set")
}

// Remove an element
delete(set, "apple")

Thus, a map with keys and empty values effectively models a set.

Is it possible to create a structure or data type… - sobes.tech