Golang Generic+Variadic Function

730 Views Asked by At

In Golang having a number of functions of some generic type

type Transformer[A, B any] func(A)(B, error)

How to define a Generic Variadic high order function that could compose such functions in general something as

func Compose[A,B,C....N any](transformers... Transformer[A,B], Transformer[B,C]...Transformer[M,N]) Transformer[A,N]
2

There are 2 best solutions below

1
NubDev On BEST ANSWER

In Go, generic variadic functions are not yet supported. However, you can achieve a similar result by using variadic arguments and recursion.

0
Spencer Connaughton On

I agree with @Volker; this is a silly thing to do in Go. I would suggest you post another question with a summary of the problem you're actually trying to solve with this construction and see if there's a way to solve you're problem that's more idiomatic.

All that being said, just for fun:

package main

import (
    "fmt"
)

type Composable[B, N any] func(in B) N

func Return[N any]() Composable[N, N] {
    return func(in N) N {
        return in
    }
}

func ToString[N any](next Composable[string, N]) Composable[int, N] {
    return func(in int) N {
        return next(fmt.Sprintf("%v", in))
    }
}

func Hello[N any](next Composable[string, N]) Composable[string, N] {
    return func(in string) N {
        return next(fmt.Sprintf("helloooo %s", in))
    }
}

func main() {
    f := ToString(Hello(Return[string]()))
    res := f(22)
    fmt.Printf("%v", res)
    // Output: helloooo 22
}

To be clear, if I saw this in a code review I would be very concerned.