0

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},
}
Olshansky
  • 5,904
  • 8
  • 32
  • 47
  • 5
    If you want to have varying function signatures in the same map, then generics are not applicable whatsoever. – Hymns For Disco Jun 04 '22 at 05:13
  • the answers in the thread you linked are still applicable, a generic container is not going to allow different types at the same time. You're still going to use `map[string]interface{}` or, if you prefer, `map[string]any` – blackgreen Jun 05 '22 at 08:38

0 Answers0