Skip to content

Instantly share code, notes, and snippets.

@mcastelino
Last active Mar 30, 2021
Embed
What would you like to do?
Golang: Create a Acyclic function graph
package main
import (
"fmt"
)
// Data that flows through the processing pipeline
type Data struct {
Type string
Data string
}
// The Handler function processes the data and then
// call the handlers downstream from itself
// Each downstream function gets its own copy of the data
type Handler func(Data) error
type HandlerChain interface {
Chain([]Handler) Handler
}
type Node struct {
Name string
}
func (n *Node) Chain(h ...Handler) Handler {
return func(d Data) error {
downstreamHandlers := h
d.Data = d.Data + "->" + n.Name
for _, f := range downstreamHandlers {
if f == nil {
fmt.Println(d.Data)
return nil
}
if err := f(d); err != nil {
return err
}
}
return nil
}
}
func main() {
a := Node{"A"}
b := Node{"B"}
c := Node{"C"}
d := Node{"D"}
e := Node{"E"}
f := Node{"F"}
path1 := b.Chain(c.Chain(nil))
path2 := d.Chain(d.Chain(e.Chain(nil)))
path3 := f.Chain(path1, path2)
tree := a.Chain(path1, path2, path3)
tree(Data{Data: "hello"})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment