Sets with map[T]struct{}
Go has no built-in set type. The stand-in is a map whose keys are the set's members and whose values go unused:
seen := make(map[string]struct{})
seen["heron"] = struct{}{} // add a member
if _, ok := seen["heron"]; ok {
fmt.Println("seen it before")
}
delete(seen, "heron") // remove a member
fmt.Println(len(seen)) // number of members
struct{} is a type with no fields that takes zero bytes, and struct{}{} is its only value. Plenty of people use map[string]bool instead because it reads shorter (if seen[x]). Both are fine. struct{} makes it clear that only the keys matter.
Why a set?
Checking "is x in this slice?" with a loop takes time proportional to the slice's length. In a set, the same check takes constant time on average. When you check thousands of times, the difference is big.
A set is also the easiest way to drop duplicates: put everything in, and len(set) is the number of distinct values.
Set operations
The two that come up most:
- Intersection: values in A and in B. Build a set from B, then check every member of A.
- Difference: values in A but not in B. The same, with the condition flipped.
inB := toSet(b)
for x := range toSet(a) {
if _, ok := inB[x]; ok {
// x is in both
}
}
Iterating a set is random too, so sort the result (slices.Sort) before returning it.
Task
Ana and Budi write down the birds they spot, one line per person, separated by commas. Some birds are written down more than once.
- Complete
toSet(xs []string) map[string]struct{}. For an empty slice, return an empty set (notnil). - Complete
both(a, b []string) []string: the values inaand inb, without duplicates, in alphabetical order. - Complete
onlyIn(a, b []string) []string: the values inathat aren't inb, without duplicates, in alphabetical order.
both and onlyIn return an empty slice (not nil) when there's nothing to return. The list function and main are ready.