tl;dr What's the best way to initialize a map of functions with different signatures in Go 1.18+?
References:
There's a great question from 10 years ago with varying answers on how to do this in the past found here: Go map of functions.
In recent past, Go also did a code-wide refactor
all: gofmt -w -r 'interface{} -> any' src
I have created a couple easy to reference examples given the best practices from the past like so:
package main
import (
"fmt"
)
func main() {
// Strongly typed - when the signature is the same
m1 := map[string]func(int, int) int{
"add": func(a, b int) int { return a + b },
"sub": func(a, b int) int { return a - b },
}
fmt.Println(m1["add"](1, 1))
fmt.Println(m1["sub"](1, 1))
// Generic interface - when the signatures differ
m2 := map[string]interface{}{
"add": func(a, b, c int) int { return a + b + c },
"sub": func(a, b int) int { return a - b },
}
fmt.Println(m2["add"].(func(int, int, int) int)(1, 1, 1))
fmt.Println(m2["sub"].(func(int, int) int)(1, 1))
}
However, I'm wondering if there have been any chances that can enable the use of variadic function and generic types. My mind is gravitating towards the following, but I don't know if this is a dead end
m3 := map[string]func(...any)any{
"add": func(a, b, c int) int { return a + b},
"sub": func(a, b int) int { return a - b},
}