Home > Article > Backend Development > How to Create Distinct Channels in Go: A Guide to Memory Leak Prevention
Distinctive Channels in Go
In Go, a common requirement is to create channels that only output distinct values. To achieve this, however, requires some additional considerations.
Implementation
A straightforward solution is to utilize a map to store encountered values. Here's a simple implementation:
<code class="go">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 }</code>
Memory Leak Concerns
When using a map to remember previously encountered values, one may worry about memory leaks. However, in this implementation, the map is bounded to the range of possible values (max - min) and is cleared upon channel closure. Therefore, there is no memory leak concern.
The above is the detailed content of How to Create Distinct Channels in Go: A Guide to Memory Leak Prevention. For more information, please follow other related articles on the PHP Chinese website!