In Go, you can find the union of two sets using maps.
In this example,
set1
and set2
.set2
and add them to set1
.package main
import "fmt"
func main() {
set1 := map[int]bool{1: true, 2: true, 3: true}
set2 := map[int]bool{3: true, 4: true, 5: true}
for k := range set2 {
set1[k] = true
}
fmt.Println(set1)
}
map[1:true 2:true 3:true 4:true 5:true]
In this example,
union
that takes two map arguments representing sets.package main
import "fmt"
func union(set1, set2 map[int]bool) map[int]bool {
for k := range set2 {
set1[k] = true
}
return set1
}
func main() {
set1 := map[int]bool{1: true, 2: true, 3: true}
set2 := map[int]bool{3: true, 4: true, 5: true}
result := union(set1, set2)
fmt.Println(result)
}
map[1:true 2:true 3:true 4:true 5:true]
In this tutorial, we learned How to find Union of Two Sets in Go language with well detailed examples.