[Solved] Daisy chain input,output channels together in golang


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

2

solved Daisy chain input,output channels together in golang