13

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?
rivalitaet
  • 386
  • 2
  • 7

3 Answers3

15

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)
}
Matt K
  • 13,370
  • 2
  • 32
  • 51
  • 3
    I just want to add that you can actually use any arbitrary type as the value, since you don't care about it. But using a `bool` always set to true has the added benefit of being able to test if an element exists simply by indexing, because when you index a key and it does not exist, it will return the zero value for the value type, which is false for booleans. – newacct Aug 12 '11 at 22:10
2

I think the map[T]bool is the best option, but another option is map[T]struct{}:

package main

func main() {
   { // example 1
      s := make(map[string]struct{})
      s["north"] = struct{}{}
      s["south"] = struct{}{}
      _, ok := s["north"]
      println(ok)
   }
   { // example 2
      s := map[string]struct{}{
         "north": {}, "south": {},
      }
      _, ok := s["north"]
      println(ok)
   }
}

it's not as easy to work with, but it takes up less memory if that is a factor for you.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
Zombo
  • 1
  • 62
  • 391
  • 407
1

There is no set implementation in golang at this point. You'll need to do it yourself or get a third party lib. Also here is a nice blog post:

https://www.openmymind.net/2011/7/15/Learning-Go-By-Benchmarking-Set-Implementation/

Christian Wilkie
  • 3,693
  • 5
  • 34
  • 49
Alex Plugaru
  • 2,209
  • 19
  • 26