2 ms·
A map[T]bool has 3 states for every key; absent, true, and false. A map[t]struct{} has 2 states for every key; absent, and present. People new to Go tend to p
by jrockway 6y ago
A map[T]bool has 3 states for every key; absent, true, and false. A map[t]struct{} has 2 states for every key; absent, and present.
People new to Go tend to pick map[T]bool or map[T]int because they're used to using bools and ints throughout their code, but struct{} is the correct value type for sets. (That is not to say that a counting set, map[T]int is useless, however. If you need that, use that!)
- majewsky 6y agoI usually use map[T]bool because if _, ok := wasTouched[thing]; !ok { touch(thing) wasTouched[thing] = struct{}{} } is way uglier than if !wasTouched[thing] { touch(thing) wasTouched[thing] = true }
- masklinn 6y agoThat doesn’t actually work unless you first fill all possible values with `false`.
- fileeditview 6y agoWrong. The whole point of this construct is that in Go maps return default values for keys that do not exist. The default value for bool is false.