Intersect And Difference Map Key Sets

Compare map key sets with intersect and difference helpers, then sort results since map iteration order is randomized on every run.

GoData Integrity

Code

gosnippet
55 lines
package main

import (
	"fmt"
	"slices"
)

// intersect:a 与 b 都有的键
func intersect(a, b map[string]bool) []string {
	var keys []string
	for key := range a {
		if b[key] {
			keys = append(keys, key)
		}
	}
	return keys
}

// difference:a 有而 b 没有的键
func difference(a, b map[string]bool) []string {
	var keys []string
	for key := range a {
		if !b[key] {
			keys = append(keys, key)
		}
	}
	return keys
}

func keySet(names ...string) map[string]bool {
	set := make(map[string]bool, len(names))
	for _, name := range names {
		set[name] = true
	}
	return set
}

func main() {
	live := keySet("orders", "billing", "auth")
	planned := keySet("billing", "auth", "search")

	both := intersect(live, planned)
	retire := difference(live, planned)
	provision := difference(planned, live)

	// map 遍历顺序随机,输出前必须排序
	slices.Sort(both)
	slices.Sort(retire)
	slices.Sort(provision)

	fmt.Println("keep both:", both)
	fmt.Println("retire:", retire)
	fmt.Println("provision:", provision)
	fmt.Println("partition check:", len(both)+len(retire) == len(live))
}

Set operations over map keys

Intersect And Difference Map Key Sets keeps everything in the functions intersect, difference, keySet and main.

Iteration happens inside for key := range a — everything outside it runs once.

Applying it

Entry signature: func intersect(a, b map[string]bool) []string

Output lines are prefixed (keep both:, retire:, provision:), so every step leaves a line you can attribute.

The demo flow inside main is keySet, intersect and difference — run the file to see it end to end.

Statements that matter

func difference(a, b map[string]bool) []string {
	var keys []string
	for key := range a {
		if !b[key] {
			keys = append(keys, key)
		}
	}
	return keys
}
func intersect(a, b map[string]bool) []string {
	var keys []string
	for key := range a {
		if b[key] {
			keys = append(keys, key)
		}
	}
	return keys
}
func keySet(names ...string) map[string]bool {
	set := make(map[string]bool, len(names))
	for _, name := range names {
		set[name] = true
	}
	return set
}

Interactive Tools for This Topic

FAQ

What does Intersect And Difference Map Key Sets print when run?
The script runs standalone; its 4 labeled outputs include `keep both:`, `retire:`, `provision:`.