Last active
February 17, 2019 21:03
-
-
Save kwilczynski/e76d4c417a9d34219a60627c4b070789 to your computer and use it in GitHub Desktop.
A simple unsorted Set type for strings in Go (backed by a map).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strings" | |
) | |
type StringSet map[string]struct{} | |
func (s *StringSet) String() string { | |
return strings.Join(s.GetStrings(), " ") | |
} | |
func (s *StringSet) Add(value string) bool { | |
_, found := (*s)[value] | |
(*s)[value] = struct{}{} | |
return !found | |
} | |
func (s *StringSet) Remove(value string) { | |
delete(*s, value) | |
} | |
func (s *StringSet) GetStrings() (values []string) { | |
values = make([]string, len(*s)) | |
i := 0 | |
for k := range *s { | |
values[i] = k | |
i++ | |
} | |
return | |
} | |
func SlicesDifference(this, other []string) []string { | |
sset := &StringSet{} | |
for _, s := range append(this, other...) { | |
sset.Add(s) | |
} | |
for _, s := range other { | |
sset.Remove(s) | |
} | |
return sset.GetStrings() | |
} | |
func main() { | |
sset := &StringSet{} | |
sset.Add("a") | |
sset.Add("b") | |
sset.Add("a") | |
sset.Add("c") | |
fmt.Println(sset) | |
fmt.Println(SlicesDifference([]string{"foo", "bar", "baz"}, []string{"baz", "quux"})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment