To filter items of a set based on a condition in Go, you can iterate over the set and selectively add items that satisfy the condition to a new set.
In this example,
numberSet
with values []int{1, 2, 3, 4, 5, 6}
.evenNumbers
.numberSet
using a for
loop.%
.evenNumbers
set.package main
import "fmt"
func main() {
numberSet := []int{1, 2, 3, 4, 5, 6}
evenNumbers := []int{}
for _, num := range numberSet {
if num % 2 == 0 {
evenNumbers = append(evenNumbers, num)
}
}
fmt.Println(evenNumbers)
}
[2 4 6]
In this example,
stringSet
with values []string{"Apple", "Banana", "Apricot", "Orange"}
.filteredStrings
.stringSet
using a for
loop.filteredStrings
set.package main
import (
"fmt"
"strings"
)
func main() {
stringSet := []string{"Apple", "Banana", "Apricot", "Orange"}
filteredStrings := []string{}
for _, str := range stringSet {
if strings.HasPrefix(str, "A") {
filteredStrings = append(filteredStrings, str)
}
}
fmt.Println(filteredStrings)
}
[Apple Apricot]
In this tutorial, we learned How to Filter Items of a Set based on a Condition in Go language with well detailed examples.