Home  >  Article  >  Backend Development  >  How do you implement a channel in Go that outputs only distinct values?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 08:20:02248browse

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
}

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!

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