Sobes.tech
Junior — Middle

Is it possible to implement a Set data structure in the Go language?

sobes.tech AI

Answer from AI

In Go, there is no built-in Set data structure, but it can be implemented using a map with keys of the desired type and values of type bool or an empty struct struct{}.

Example of implementing a set of strings:

package main

import "fmt"

func main() {
    set := make(map[string]struct{})

    // Adding elements
    set["apple"] = struct{}{}
    set["banana"] = struct{}{}

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

    // Removing an element
    delete(set, "banana")
}

Using an empty struct struct{} instead of bool saves memory, as struct{} occupies 0 bytes.

Is it possible to implement a Set data structure in… - sobes.tech