To remove items from a set (represented as a map) based on a condition in Go, you can iterate over the map and delete items that meet the condition.
In this example,
numberSet
to represent the set, with integer keys and boolean values: numberSet := map[int]bool{1: true, 2: true, 3: true, 4: true, 5: true};
.for
loop.delete
function.package main
import "fmt"
func main() {
numberSet := map[int]bool{1: true, 2: true, 3: true, 4: true, 5: true}
fmt.Println("Original Set:", numberSet)
for num := range numberSet {
if num % 2 == 0 {
delete(numberSet, num)
}
}
fmt.Println("Set after removing even numbers:", numberSet)
}
Original Set: map[1:true 2:true 3:true 4:true 5:true] Set after removing even numbers: map[1:true 3:true 5:true]
In this example,
stringSet
to represent the set, with string keys and boolean values: stringSet := map[string]bool{"apple": true, "banana": true, "orange": true, "kiwi": true};
.for
loop.delete
function.package main
import "fmt"
func main() {
stringSet := map[string]bool{"apple": true, "banana": true, "orange": true, "kiwi": true}
fmt.Println("Original Set:", stringSet)
for str := range stringSet {
if len(str) > 4 {
delete(stringSet, str)
}
}
fmt.Println("Set after removing strings longer than 4 characters:", stringSet)
}
Original Set: map[apple:true banana:true orange:true kiwi:true] Set after removing strings longer than 4 characters: map[kiwi:true]
In this tutorial, we learned How to Remove Items from Set based on a Condition in Go language with well detailed examples.