dongzhaiqiang6108 2014-08-13 14:24
浏览 27
已采纳

在Go中编写独特渠道的正确方法是什么?

I am a beginner in go.

I am trying to figure out an easy way to implement a channel that only output distinct values.

What I want to do is this:

package example

import (
    "fmt"
    "testing"
)

func TestShouldReturnDistinctValues(t *testing.T) {

    var c := make([]chan int)

    c <- 1
    c <- 1
    c <- 2
    c <- 2
    c <- 3

    for e := range c {
        // only print 1, 2 and 3.
        fmt.println(e)      
    }
}

Should I be concern about memory leak here if I were to use a map to remember previous values?

Thanks.

  • 写回答

2条回答 默认 最新

  • dq1685513999 2014-08-13 14:32
    关注

    You really can't do that, you'd have to keep a track of the values somehow, a map[int]struct{} is probably the most memory efficient way.

    A simple example:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了