A set refers to a collection of unordered items. Sets are unique and do not allow duplicate values in a single entry.
If you work with Go programming, you quickly realize there are no concept sets. However, we can play some tricks with maps and structs to create a set.
Golang Create Set
Fundamentally, sets are a collection of unique values. We can use a map with an empty struct to represent them.
We can express this syntax as:
Since an empty struct takes 0 bytes, the set is a very efficient method of implementing a set.
The following example creates a simple set using the previous syntax.
type void struct{}
var member void
func main() {
set := make(map[string]void)
}
The previous example creates an empty set with a string as the key and an empty struct.
Golang Add Elements to Set
Once we have the set declared, we can add elements to the map using the map syntax. An example is as illustrated below:
import "fmt"
type void struct{}
var member void
func main() {
set := make(map[string]void)
set["apple"] = member
set["orange"] = member
set["mango"] = member
fmt.Println(set)
}
In the previous example, we assign new values to the set.
Golang Set Iteration
We can iterate over a map using the classic for loop and range operator. A code example is shown below:
import "fmt"
type void struct{}
var member void
func main() {
set := make(map[string]void)
set["apple"] = member
set["orange"] = member
set["mango"] = member
for k := range set {
fmt.Println(k)
}
}
The loop construct above should return the elements in the set:
mango
apple
orange
Golang Delete Set Element
We can remove members from a set using the Delete method. For example, to remove the element “apple” from the set, we can do:
import “fmt”
type void struct{}
var member void
func main() {
set := make(map[string]void)
set[“apple”] = member
set[“orange”] = member
set[“mango”] = member
delete(set, “apple”)
for k := range set {
fmt.Println(k)
}
}
The Delete method takes the name of the set and the element to remove.
Golang Check If Element Exists
We can check if an element exists within a set using the syntax shown:
fmt.Println(“element exists”)
} else {
fmt.Println(“element not found”)
}
The previous code should execute the if block when the element is in the set and the else block if otherwise.
Conclusion
This article explored how to implement a set type in the Go programming language. Before using the set for performance critical environments, check how a set affects the performance. We hope you found this article helpful. Check other Linux Hint articles for more tips and information.