Distinct Channel Implementation in Go
In Go, implementing a channel that outputs distinct values requires a mechanism to keep track of previously seen values.
One common approach is to use a map data structure, as suggested in the answer:
func UniqueGen(min, max int) <-chan int { m := make(map[int]struct{}, max-min) ch := make(chan int) go func() { for i := 0; i < 1000; i++ { v := min + rand.Intn(max) if _, ok := m[v]; !ok { ch <- v m[v] = struct{}{} } } close(ch) }() return ch }
This function generates a channel that produces up to 1000 distinct integers within the specified range. It maintains a map where the keys represent the values seen so far. If a new value is encountered (not present in the map), it is sent on the channel, and the map is updated to record its occurrence.
As for the memory leak concerns, using a map for this purpose is generally considered memory-efficient. Maps in Go reference the key values, so the memory consumption remains proportional to the number of distinct values encountered. However, it's important to note that the map will continue to hold the references to previous values, so if the number of distinct values becomes very large, it could still consume a significant amount of memory.
The above is the detailed content of How do you implement a channel in Go that outputs only distinct values?. For more information, please follow other related articles on the PHP Chinese website!