Golang's Curious Lack of Set Data Structure
In Golang, the fundamental need for a set data structure has led to the puzzling question: Why isn't one natively provided? Drawing inspiration from Google's influential Guava library, why did the designers of Golang omit support for such a fundamental structure, forcing developers to craft their own implementations?
The answer lies in the simplicity of constructing sets using maps. As demonstrated in the provided code snippet, maps can be leveraged to create sets. Key operations such as checking for existence, adding, removing, and performing set operations (union, intersection) can be implemented easily.
s := map[int]bool{5: true, 2: true} _, ok := s[6] // check for existence s[8] = true // add element delete(s, 2) // remove element // Union s_union := map[int]bool{} for k, _ := range s1{ s_union[k] = true } for k, _ := range s2{ s_union[k] = true } // Intersection s_intersection := map[int]bool{} if len(s1) > len(s2) { s1, s2 = s2, s1 // better to iterate over a shorter set } for k,_ := range s1 { if s2[k] { s_intersection[k] = true } }
While these map-based implementations are sufficient for most practical scenarios, some may argue that a native set implementation would simplify and enhance code readability. Nonetheless, for Golang developers, understanding the use of maps as sets is crucial for both problem-solving and efficient resource utilization.
The above is the detailed content of Why Doesn't Golang Have a Native Set Data Structure?. For more information, please follow other related articles on the PHP Chinese website!