In Go, you can use a map with empty structs to create a collection of unique strings.
In this example,
stringSet
where string keys represent unique strings.struct{}
as values to minimize memory usage.package main
import (
"fmt"
)
func main() {
// Create a map for string set
stringSet := make(map[string]struct{})
// Add strings to the set
stringSet["Apple"] = struct{}{}
stringSet["Banana"] = struct{}{}
stringSet["Cherry"] = struct{}{}
// Print the set
fmt.Println(stringSet)
}
map[Apple:{} Banana:{} Cherry:{}]
In this example,
package main
import (
"fmt"
)
func main() {
// Check if the set contains a string
containsBanana := stringSet["Banana"]
fmt.Printf("Set contains Banana: %t\n", containsBanana != nil)
}
Set contains Banana: true
In this tutorial, we learned How to create a Set of Strings in Go language with well detailed examples.