To create a set in Go, you can use a map where the keys represent the elements of the set. Go does not have a built-in set data structure, but you can simulate one using a map.
In this example,
createNumberSet
that takes a variadic parameter numbers
of type int
. This parameter represents the elements to be added to the set.set
where the keys are of type int
.for
loop to iterate over the provided numbers and add them as keys to the set map with a value of true
.createNumberSet
with some numbers and store the result in a variable named numberSet
.package main
import (
"fmt"
)
func createNumberSet(numbers ...int) map[int]bool {
set := make(map[int]bool)
for _, num := range numbers {
set[num] = true
}
return set
}
func main() {
numberSet := createNumberSet(1, 2, 3, 4, 5)
fmt.Println("Number Set:", numberSet)
}
Number Set: map[1:true 2:true 3:true 4:true 5:true]
In this example,
createStringSet
that takes a variadic parameter strings
of type string
. This parameter represents the elements to be added to the set.set
where the keys are of type string
.for
loop to iterate over the provided strings and add them as keys to the set map with a value of true
.createStringSet
with some strings and store the result in a variable named stringSet
.package main
import (
"fmt"
)
func createStringSet(strings ...string) map[string]bool {
set := make(map[string]bool)
for _, str := range strings {
set[str] = true
}
return set
}
func main() {
stringSet := createStringSet("apple", "banana", "orange")
fmt.Println("String Set:", stringSet)
}
String Set: map[apple:true banana:true orange:true]
In this tutorial, we learned How to create a Set of size N in Go language with well detailed examples.