Set
However, you can repurpose the map
type to create a set-like structure.
// Create a set using a mapset := make(map[string]struct{})
// Add elements to the setset["apple"] = struct{}{}set["banana"] = struct{}{}set["orange"] = struct{}{}
// Check if an element is in the setif _, exists := set["banana"]; exists { fmt.Println("banana is in the set")}
// Remove an element from the setdelete(set, "banana")
// Check if an element is in the setif _, exists := set["banana"]; !exists { fmt.Println("banana is not in the set anymore")}
The struct{}{}
is an empty struct type, which takes no memory. This allows you to use the map as a set without storing any values.
While this is not a true set implementation, it works well for most use cases.