How to Use a Map as a Set in Go

Use a map with boolean values to simulate a set in Go for tracking unique items efficiently.

Use a map[KeyType]bool where the key is your unique value and the boolean is always true to simulate a set. Check for existence with the comma-ok idiom to distinguish between missing keys and zero values.

mySet := make(map[string]bool)

// Add an item
mySet["apple"] = true

// Check if an item exists
if exists, ok := mySet["apple"]; ok {
    // "apple" is in the set
}

// Remove an item
delete(mySet, "apple")