Skip to content

Latest commit

 

History

History
97 lines (68 loc) · 1.31 KB

collections.sets.md

File metadata and controls

97 lines (68 loc) · 1.31 KB

Overview

  1. Key features & common operations on sets
  2. See maps doc

Key Concepts

  1. Implement using map[T]bool
  2. Alternative: map[T]struct{} (empty struct as value)
    1. Set operations are a little more verbose, but consume less memory
    2. See struct doc

Creation

visited := make(map[string]bool)

visited["a"] = true
visited["b"] = true

if visited["a"] {
    fmt.Print("yep")
}

Size

theSize := len(theSet)

Insert/Update

visited := make(map[string]bool)

visited["a"] = true

Remove

delete(theSet, "foo")

Check for value

visited["a"] = true
//...

if visited["a"] {
    fmt.Print("yep")
}

Iterate

  1. Iteration order is random
for value, found := range visited {
    if !found {
        continue
    }

    fmt.Println(value)
}

Shallow copy

srcSet := make(map[string]bool)
//...

destSet := make(map[string]bool, len(srcSet))
for value, contains := range srcSet {
    if !contains {
        continue
    }

    destSet[value] = true
}

Acceptable values

  1. A "set" can only structs if all its fields are comparable

Sort

  • See sorting doc

  • TODO: json unmarshal

  • TODO: json marshal

Other Resources

  1. TODO