In Go, you can perform set operations such as union, intersection, and difference using the built-in map
data structure. Here's an example of how you can do it:
package main
import "fmt"
func main() {
// Example sets
setA := []int{1, 2, 3, 4, 5}
setB := []int{4, 5, 6, 7}
// Union
union := make(map[int]bool)
for _, val := range setA {
union[val] = true
}
for _, val := range setB {
union[val] = true
}
// Intersection
intersection := make(map[int]bool)
for _, val := range setA {
if contains(setB, val) {
intersection[val] = true
}
}
// Difference
difference := make(map[int]bool)
for _, val := range setA {
if !contains(setB, val) {
difference[val] = true
}
}
fmt.Println(union) // Output: map[1:true 2:true 3:true 4:true 5:true 6:true 7:true]
fmt.Println(intersection) // Output: map[4:true 5:true]
fmt.Println(difference) // Output: map[1:true 2:true 3:true]
}
// Function to check if a value is present in a slice
func contains(slice []int, val int) bool {
for _, item := range slice {
if item == val {
return true
}
}
return false
}
In this example, we have two sets setA
and setB
, represented as slices of integers. We create a map
called union
and iterate over the elements of both sets to add them to the union
map.
For intersection, we create another map
called intersection
and iterate over the elements of setA
. If an element is present in setB
, we add it to the intersection
map.
For difference, we create a map
called difference
and iterate over the elements of setA
. If an element is not present in setB
, we add it to the difference
map.
Finally, we print the union
, intersection
, and difference
maps to display the result.