Sobes.tech
Junior — Middle

How can you implement a Set data structure in Go?

sobes.tech AI

Answer from AI

The Go language does not have a built-in Set type, but it can be implemented using a map with keys of the desired type and values of bool or an empty struct struct{}. For example, a set of strings can be created as follows:

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")

    // Iterating over elements
    for key := range set {
        fmt.Println(key)
    }
}

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

How can you implement a Set data structure in Go… - sobes.tech