Home >Backend Development >Golang >How to Create a Channel of Unique Integers in Go?

How to Create a Channel of Unique Integers in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 18:50:30389browse

How to Create a Channel of Unique Integers in Go?

Creating Distinct Channels in Go

In this programming question, a beginner in Go seeks an efficient approach to defining a channel that outputs unique values. The specific requirement is to create a channel that accepts integer values and only transmits distinct integers. The goal is to avoid duplicate integers in the output.

One of the responses suggests using a map to store previously transmitted values to achieve this functionality. While this method can effectively eliminate duplicate values, the memory usage is a consideration. The map data structure requires allocating and maintaining a collection of key-value pairs, which can potentially lead to memory leaks if not managed carefully.

To provide a practical solution, the following code snippet introduces the UniqueGen function, which generates a channel of unique integers within a specified range:

<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>

The UniqueGen function uses a map to record transmitted integers. It starts a goroutine that repeatedly generates integers within the specified range. For each generated value, the function checks if it has already been transmitted by looking it up in the map. If not, it sends the integer over the channel and records it in the map. This process effectively filters out duplicate values, ensuring that only distinct integers are transmitted through the channel.

Using the UniqueGen function, the following test case can be implemented to demonstrate the behavior:

<code class="go">func TestShouldReturnDistinctValues(t *testing.T) {
    var c = make([]chan int)

    c <- UniqueGen(1, 1000)

    for e := range c {
        // only print distinct values 
        fmt.println(e)
    }
}</code>

This test case will generate a channel of 1000 unique integers and print them to the console. By utilizing the UniqueGen function, the test can ensure that it outputs distinct values.

The above is the detailed content of How to Create a Channel of Unique Integers in Go?. 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