Home > Backend Development > Golang > 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
Release: 2024-10-29 04:40:02
Original
470 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template