To find the intersection of two sets in Go, you can create a map for one set and then iterate through the other set to check for common elements.
In this example,
set1
and set2
.set1
and store its elements in a map named set1Map
.set2
and check if each element is present in set1Map
.intersection
slice.package main
import "fmt"
func main() {
set1 := []int{1, 2, 3, 4, 5}
set2 := []int{4, 5, 6, 7, 8}
set1Map := make(map[int]bool)
for _, num := range set1 {
set1Map[num] = true
}
var intersection []int
for _, num := range set2 {
if set1Map[num] {
intersection = append(intersection, num)
}
}
fmt.Println(intersection)
}
[4 5]
In this example,
set1
and set2
.set1
using a nested loop and check if each element is present in set2
.intersection
slice.package main
import "fmt"
func main() {
set1 := []int{1, 2, 3, 4, 5}
set2 := []int{4, 5, 6, 7, 8}
var intersection []int
for _, num1 := range set1 {
for _, num2 := range set2 {
if num1 == num2 {
intersection = append(intersection, num1)
}
}
}
fmt.Println(intersection)
}
[4 5]
In this tutorial, we learned How to find Intersection of Two Sets in Go language with well detailed examples.