Skip to content

Instantly share code, notes, and snippets.

@soypat
Last active December 11, 2022 20:13
Show Gist options
  • Save soypat/00eb8392f24c584dc4dccf5383f7488d to your computer and use it in GitHub Desktop.
Save soypat/00eb8392f24c584dc4dccf5383f7488d to your computer and use it in GitHub Desktop.
Set operations for Go.
package sets
// a | b
func union[T comparable](a, b map[T]struct{}) map[T]struct{} {
c := make(map[T]struct{})
for k := range a {
c[k] = struct{}{}
}
for k := range b {
c[k] = struct{}{}
}
return c
}
// a & b
func intersection[T comparable](a, b map[T]struct{}) map[T]struct{} {
c := make(map[T]struct{})
if len(a) > len(b) {
a, b = b, a // Put smallest map in a to reduce iterations, thanks Mario R.
}
for k := range a {
if _, ok := b[k]; ok {
c[k] = struct{}{}
}
}
return c
}
// a-b
func difference[T comparable](a, b map[T]struct{}) map[T]struct{} {
c := make(map[T]struct{})
for k := range a {
if _, ok := b[k]; !ok {
c[k] = struct{}{}
}
}
return c
}
// a-b | b-a
func symdiff[T comparable](a, b map[T]struct{}) map[T]struct{} {
c := make(map[T]struct{})
for k := range a {
if _, ok := b[k]; !ok {
c[k] = struct{}{}
}
}
for k := range b {
if _, ok := a[k]; !ok {
c[k] = struct{}{}
}
}
return c
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment