Skip to content

Instantly share code, notes, and snippets.

@mcastelino
Last active March 31, 2021 03:37
Show Gist options
  • Save mcastelino/02ea417cec7bba8e7e8f2db09a7988c4 to your computer and use it in GitHub Desktop.
Save mcastelino/02ea417cec7bba8e7e8f2db09a7988c4 to your computer and use it in GitHub Desktop.
Golang Generics Acyclic Function Graph
package main
import (
"fmt"
)
// Data that flows through the processing pipeline
type Data[T any] struct {
Type string
Path string
Value T
}
// 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[T any] func(Data[T]) error
type Node[T any] struct {
Name string
}
func (n *Node[T]) Chain(h ...Handler[T]) Handler[T] {
return func(d Data[T]) error {
downstreamHandlers := h
d.Path = d.Path + fmt.Sprintf("-> (%s, %v)", n.Name, d.Value)
for _, f := range downstreamHandlers {
if f == nil {
fmt.Println(d.Path)
return nil
}
if err := f(d); err != nil {
return err
}
}
return nil
}
}
func main() {
a := Node[string]{"A"}
b := Node[string]{"B"}
c := Node[string]{"C"}
d := Node[string]{"D"}
e := Node[string]{"E"}
f := Node[string]{"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[string]{Value: "hello"})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment