Do Sets exist in Go? (like in Python)

Issue

Is there any Go collection similar to ‘Set’s in python?

alternatives:

  • Is there an easy way of implementing Sets in Go?
  • Is there any method to eliminate duplicates in a slice?

Solution

You could just have a map[whatevertype]bool and set the value to true. You could add every element in a slice as a map key, then use a range to get only the unique ones back out.

package main
import "fmt"
func main() {
    m := make(map[string]bool)
    s := make([]string, 0)
    s = append(s, "foo")
    s = append(s, "foo")
    s = append(s, "foo")
    s = append(s, "bar")
    s = append(s, "bar")
    for _, r := range s {
        m[r] = true
    }
    s = make([]string, 0)
    for k, _ := range m {
        s = append(s, k)
    }
    fmt.Printf("%v\n", s)
}

Answered By – Matt K

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.