I'm studying existing go-source-codes and notice the following approach too often:
intSet := map[int]struct{}{}
vals := []int{5, 10, 2, 5, 8, 7, 3, 9, 1, 2, 10}
for _, v := range vals {
intSet[v] = struct{}{}
}
if _, ok := intSet[5]; ok {
fmt.Println("5 is in the set")
}
After initial syntax-related difficulties, I understood the code but using structs as values does not seem logical to me; what do I miss?
Edit: Source code from the book Learning Go
CodePudding user response:
Because the struct{}{}
cost zero storage usage which is called an empty struct.
So it's very useful for only want to use the map as the set.