Implementing a set using a map
A set is useful to remove duplicates from a collection of values. Maps can be used as sets efficiently by utilizing a zero-size value structure.
How to do it...
Use a map whose key type is the element type of the set, and whose value type is struct{}
:
stringSet := make(map[string]struct{})
Add values to the set with the struct{}{}
value:
stringSet[value]=struct{}{}
Check for value existence using the two-value version of map lookup:
if _,exists:=stringSet[str]; exists { // String str exists in the set }
A map is not ordered. If the ordering of elements is important, keep a slice with the map:
// Remove duplicate inputs from the input, preserving order func DedupOrdered(input []string) []string { set:=make(map[string]struct{}) output:=make([]string,0,len(input)) for _,in:=range input { if _,exists:=set[in]; exists { ...