Use maps as sets
Use maps as sets
A set represents distinct members without associated payloads. In Go, map[T]struct{} is a conventional set for comparable keys T. The empty struct has zero size as a value, but the map still requires storage for keys and bookkeeping. Use comma-ok membership rather than the zero value.
package main
import ( "fmt")
func main() { s := map[string]struct{}{} for _, v := range []string{"tea", "coffee", "tea"} { s[v] = struct{}{} } _, ok := s["tea"] fmt.Println(len(s), ok) delete(s, "tea") _, ok = s["tea"] fmt.Println(ok)}Duplicate insertion replaces an existing entry rather than adding a second member. Deleting a missing key is harmless. A nil map can be read but not assigned into; initialize it before insertion. Map traversal order is unspecified.
Expected output:
2 truefalseIntersect two sets
package main
import ( "fmt" "slices")
func intersect(a, b map[int]struct{}) []int { var out []int for k := range a { if _, ok := b[k]; ok { out = append(out, k) } } slices.Sort(out) return out}func main() { a := map[int]struct{}{1: {}, 3: {}, 5: {}} b := map[int]struct{}{3: {}, 5: {}, 7: {}} fmt.Println(intersect(a, b), intersect(a, nil))}Iterate one set and look up each key in the other. Sorting the result supplies deterministic display order. Hash-map operations are typically efficient but the language specification does not guarantee constant-time lookup. The result is a separate slice, not a live view.
Expected output:
[3 5] []Try it locally
Build the union of {1,2} and {2,3} in a map[int]struct{}; print its size and whether 4 is present.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Data structures 03: Use maps as sets
Check the lesson objective before moving on.
How do you distinguish a missing key in map[int]struct{}?
Why sort the intersection result?