Go: How to implement a set
The idiomatic way to implement a set in Go is to use a map, where the keys in the map represent the elements in the set.
For simplicity true
is typically used as dummy value.
Set operations are then encoded as operations on a map.
Alternative representation
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 require any memory.
Some set operations differ slighly. You typically declare…
type void struct{}
var member void
…and do the following:
Operation | Code |
---|---|
Create empty set |
|
Add an element |
|
Remove an element |
|
Iterate over a set |
|
Size of set |
|
Check containment |
|
Operation | Code |
---|---|
Create empty set |
|
Add an element |
|
Remove an element |
|
Iterate over a set |
|
Size of set |
|
Check containment |
|