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

时间:2018-03-28 13:27:32

标签: go goroutine

我有以下界面和结构

usage: test.py [-h] [--gpio] [--serial] [--log] [--debug LEVEL] [--pin PIN]
               [--verbose]

optional arguments:
  -h, --help     show this help message and exit
  --gpio         Use GPIO.
  --serial       Make a serial connection.
  --log          Log actions.
  --debug LEVEL  Debug level.
  --pin PIN      Pin number.
  --verbose      Increase level of verbosity.

现在我正在尝试雏菊接口以创建如下所示的管道

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

type Pipline struct {
    Steps []core.PiplineStep
}

但是编译器说这不可能吗?

我得到以下错误'声明并且未使用'我试图关注但看起来所有步骤都接收相同的陈

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

1 个答案:

答案 0 :(得分:0)

如果要在每次迭代中重复使用它,必须在循环外声明通道变量(为简洁起见,省略了错误和上下文):

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
}

在操场上试试:https://play.golang.org/p/ItVLUBRpNA1