Home  >  Article  >  Backend Development  >  How to Create Distinct Channels in Go: A Guide to Memory Leak Prevention

How to Create Distinct Channels in Go: A Guide to Memory Leak Prevention

Linda Hamilton
Linda HamiltonOriginal
2024-10-29 04:40:02433browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn