drhgzx4727 2018-03-28 13:27
浏览 68
已采纳

菊链输入,输出通道一起在golang中

I have the following interface and struct

type PiplineStep interface {
    Do(ctx context.Context, in <-chan Message) (<-chan Message, <-chan error, error)
}

type Pipline struct {
    Steps []core.PiplineStep
}

Now I am trying to daisy the interfaces to create a pipeline like the following

    for _, step := range p.Steps {
        out, errc, err := step.Do(ctx, out)
        errcList = append(errcList, errc)

        if err != nil {
            errc <- err
            return
        }

        select {
        case outer <- msg:
        case <-ctx.Done():
            return
        }
    }

But the compiler says no is this possible?

I get the following Error 'out declared and not used' i have attempted following but it appears that all steps are receiving the same chan

    for _, step := range p.Steps {
        var tmpOut <-chan core.Message
        tmpOut = out
        tmpOut, errcTmp, err := step.Do(ctx, tmpOut)
        errcList = append(errcList, errcTmp)

        if err != nil {
            errc <- err
            return
        }
        select {
        case out <- msg:
        case <-ctx.Done():
            return
        }
    }
  • 写回答

1条回答 默认 最新

  • dtyz76562 2018-03-28 14:39
    关注

    You have to declare your channel variable outside the loop if you want to re-use it in each iteration (errors and context omitted for brevity):

    package main
    
    import "fmt"
    
    func main() {
        var pipeline Pipeline
    
        pipeline.Steps = append(pipeline.Steps,
                AddBang{},
                AddBang{},
                AddBang{},
        )
    
        src := make(chan Message)
        pipe := src
    
        for _, s := range pipeline.Steps {
                pipe = s.Do(pipe)
        }
    
        go func() {
                src <- "msg 1"
                src <- "msg 2"
                src <- "msg 3"
        }()
    
        fmt.Println(<-pipe)
        fmt.Println(<-pipe)
        fmt.Println(<-pipe)
    }
    
    type Message string
    
    type Pipeline struct {
        Steps []PipelineStep
    }
    
    type PipelineStep interface {
        Do(in chan Message) chan Message
    }
    
    type AddBang struct{}
    
    func (AddBang) Do(in chan Message) chan Message {
        out := make(chan Message)
        go func() {
                defer close(out)
                for m := range in {
                        out <- m + "!"
                }
        }()
        return out
    }
    

    Try it on the playground: https://play.golang.org/p/ItVLUBRpNA1

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大