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

我是围棋初学者。


我试图找出一种简单的方法来实现只输出不同值的通道。


我想做的是这样的:


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)      

    }

}

如果我要使用地图来记住以前的值,我是否应该担心内存泄漏?


BIG阳
浏览 179回答 2
2回答

大话西游666

你真的不能那样做,你必须以某种方式跟踪这些值,amap[int]struct{}可能是最有效的内存方式。一个简单的例子:func UniqueGen(min, max int) <-chan int {&nbsp; &nbsp; m := make(map[int]struct{}, max-min)&nbsp; &nbsp; ch := make(chan int)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; for i := 0; i < 1000; i++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; v := min + rand.Intn(max)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if _, ok := m[v]; !ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ch <- v&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; m[v] = struct{}{}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; close(ch)&nbsp; &nbsp; }()&nbsp; &nbsp; return ch}

largeQ

我以前做过类似的事情,除了我的问题是按升序输出输入。你可以通过添加一个中间 go 例程来做到这一点。这是一个例子:package mainfunc main() {&nbsp; &nbsp; input, output := distinct()&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; input <- 1&nbsp; &nbsp; &nbsp; &nbsp; input <- 1&nbsp; &nbsp; &nbsp; &nbsp; input <- 2&nbsp; &nbsp; &nbsp; &nbsp; input <- 2&nbsp; &nbsp; &nbsp; &nbsp; input <- 3&nbsp; &nbsp; &nbsp; &nbsp; close(input)&nbsp; &nbsp; }()&nbsp; &nbsp; for i := range output {&nbsp; &nbsp; &nbsp; &nbsp; println(i)&nbsp; &nbsp; }}func distinct() (input chan int, output chan int) {&nbsp; &nbsp; input = make(chan int)&nbsp; &nbsp; output = make(chan int)&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; set := make(map[int]struct{})&nbsp; &nbsp; &nbsp; &nbsp; for i := range input {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if _, ok := set[i]; !ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; set[i] = struct{}{}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; output <- i&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; close(output)&nbsp; &nbsp; }()&nbsp; &nbsp; return}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go