Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Sets exist in Go? (like in Python)

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?
like image 429
rivalitaet Avatar asked Aug 12 '11 15:08

rivalitaet


People also ask

Are there sets in Go?

Although Go doesn't have sets natively, we can make use of maps to act the same way. We were able to execute all operations that are characteristic of a set, with the same time complexity of O(1) for adding and removing members from a set.

Do sets exist in Python?

Creating Python Sets It can have any number of items and they may be of different types (integer, float, tuple, string etc.). But a set cannot have mutable elements like lists, sets or dictionaries as its elements. Try the following examples as well.

Are sets immutable in Python?

Set Items. Items of a set in python are immutable (unchangeable), do not duplicate values, and unordered.


2 Answers

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)
}
like image 184
Matt K Avatar answered Oct 10 '22 21:10

Matt K


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.

like image 31
Zombo Avatar answered Oct 10 '22 19:10

Zombo