Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Golang Generics Acyclic Function Graph
package main
import (
// 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 {
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