How do you implement a channel in Go that outputs only distinct values?

Barbara Streisand
Release: 2024-10-28 08:20:02
Original
254 people have browsed it

How do you implement a channel in Go that outputs only distinct values?

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!