2

2 basic set implementations

 3 years ago
source link: https://yourbasic.org/golang/implement-set/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

2 basic set implementations

yourbasic.org/golang
eggs-in-basket.jpg

Map implementation

The idiomatic way to implement a set in Go is to use a map.

set := make(map[string]bool) // New empty set
set["Foo"] = true            // Add
for k := range set {         // Loop
    fmt.Println(k)
}
delete(set, "Foo")    // Delete
size := len(set)      // Size
exists := set["Foo"]  // Membership

Alternative

If the memory used by the booleans is an issue, which seems unlikely, you could replace them with empty structs. In Go, an empty struct typically doesn’t use any memory.

type void struct{}
var member void

set := make(map[string]void) // New empty set
set["Foo"] = member          // Add
for k := range set {         // Loop
    fmt.Println(k)
}
delete(set, "Foo")      // Delete
size := len(set)        // Size
_, exists := set["Foo"] // Membership

Bitset implementation

bits-thumb.jpg

For small sets of integers, you may want to consider a bitset, a small set of booleans, often called flags, represented by the bits in a single number.

See Bitmasks and flags for a complete example.

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK