Created
September 12, 2017 10:15
-
-
Save prl900/860216af9f4bbe1af5d7ce1a7bd79c8c to your computer and use it in GitHub Desktop.
Example of a Go pipeline
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
type Stringer struct { | |
In chan *string | |
Out chan *string | |
Error chan error | |
Suffix string | |
} | |
func NewStringer(sufx string, errChan chan error) *Stringer { | |
return &Stringer{ | |
In: make(chan *string, 100), | |
Out: make(chan *string, 100), | |
Error: errChan, | |
Suffix: sufx, | |
} | |
} | |
func (s *Stringer) Run() { | |
defer close(s.Out) | |
for msg := range s.In { | |
newMsg := *msg + s.Suffix | |
s.Out <- &newMsg | |
} | |
} | |
func InstantiateStringPipeline(errChan chan error, msg *string) chan *string { | |
a := NewStringer("A", errChan) | |
go func() { | |
a.In <- msg | |
close(a.In) | |
}() | |
b := NewStringer("B", errChan) | |
c := NewStringer("C", errChan) | |
b.In = a.Out | |
c.In = b.Out | |
go a.Run() | |
go b.Run() | |
go c.Run() | |
return c.Out | |
} | |
func main() { | |
errChan := make(chan error) | |
msg := "HOLA" | |
select { | |
case res := <-InstantiateStringPipeline(errChan, &msg): | |
fmt.Println(*res) | |
return | |
case err := <-errChan: | |
fmt.Println("Error", err) | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment