In the following code, I define a Pipe
struct that help use pipe the result of one function into another function.
package main
import (
"fmt"
"strings"
)
type Pipe[Input any, Output any] struct {
output Output
}
func (p *Pipe[Input, Output]) Output() Output {
return p.output
}
func First[Input any, Output any](input Input, f func(Input) Output) *Pipe[Input, Output] {
return &Pipe[Input, Output]{
output: f(input),
}
}
func Then[Input any, Output any, Any any](pipe *Pipe[Any, Input], f func(Input) Output) *Pipe[Input, Output] {
return &Pipe[Input, Output]{
output: f(pipe.output),
}
}
func main() {
var (
funA = func(i int) float64 { return float64(i) }
funB = func(f float64) string { return fmt.Sprintf("%f", f) }
funC = func(s string) string { return strings.TrimRight(s, "0") }
)
p1 := First(7, funA)
p2 := Then(p1, funB)
p3 := Then(p2, funC)
fmt.Println(p3.Output()) // outputs "7."
}
I would like to define Then
as a method of Pipe
, so that I could do First(7, funA).Then(funB).Then(funC).Output()
, however, I get the error syntax error: method must have no type parameters
.
Is there any way to make First(7, funA).Then(funB).Then(funC).Output()
feasible?
Note: I wish to keep the compile time check of types. I wish to avoid having to use functions defined as func(any) any
and have to type assert the input and output types at runtime.