drz5553 2017-03-09 12:38
浏览 21

转到:转换后的频道

Let's say I have an int channel in Go:

theint := make(chan int)

I want to wrap this channel in a new channel called incremented

incremented := make(chan int)

Such that:

go func() { theint <- 1 }
    <- incremented // 2

appended can be assumed to be the only one that reads from the int.

It will work if a run a goroutine in the background

go func() {
   for num := range theint {
      incremented <- num + 1
   }
}

However, I prefer to do it without a goroutine since I can't control it in my context.

Is there a simpler way to do it?

One thing that came to mind is python's yield:

for num in theint:
     yield num + 1

Is something like this possible in go?

  • 写回答

2条回答 默认 最新

  • dsaff82024 2017-03-09 13:48
    关注

    Generator pattern

    What you are trying to implement is generator pattern. To use channels and goroutines for implementation of this pattern is totally common practice.

    However, I prefer to do it without a goroutine since I can't control it in my context.

    I believe the problem is deadlock

    fatal error: all goroutines are asleep - deadlock!

    To avoid deadlocks and orphaned (not closed) channels use sync.WaitGroup. This is an idiomatic way to control goroutines.

    Playground

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func incGenerator(n []int) chan int {
        ch := make(chan int)
        var wg sync.WaitGroup
        wg.Add(len(n))
    
        for _, i := range n {
            incremented := i + 1
            go func() {
                wg.Done()
                ch <- incremented
            }()
        }
    
        go func() {
            wg.Wait()
            close(ch)
        }()
    
        return ch
    }
    
    func main() {
        n := []int{1, 2, 3, 4, 5}
        for x := range incGenerator(n) {
            fmt.Println(x)
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算