How can you create a slice of functions with different signatures in Go?
Go's type system is statically typed, which means that functions must have a fixed signature at compile time. However, it can be useful to create slices of functions that can accept arguments of different types or numbers.
While the provided code is functional, it requires using a switch statement to handle each function signature type. A more concise and flexible solution is to use reflection.
Here's an example:
package main import ( "fmt" "reflect" ) type Executor func(...interface{}) func main() { functions := []Executor{ func(a, b int) { fmt.Println(a + b) }, func(s string) { fmt.Println(s) }, func() { fmt.Println("No arguments") }, } for _, f := range functions { numIn := reflect.TypeOf(f).NumIn() args := make([]reflect.Value, numIn) for i := 0; i < numIn; i++ { switch reflect.TypeOf(f).In(i).Kind() { case reflect.Int: args[i] = reflect.ValueOf(12) case reflect.String: args[i] = reflect.ValueOf("Hello") default: args[i] = reflect.Value{} } } f.Call(args) } }
In this solution, we create a slice of Executor functions, which are functions that accept any number of arguments. The reflect package is used to determine the number and types of arguments expected by each function and generate the corresponding reflect.Value slice.
Using reflection allows us to dynamically call functions with varying signatures without the need for a type switch or interface{} slices.
The above is the detailed content of How Can I Create a Slice of Functions with Different Signatures in Go?. For more information, please follow other related articles on the PHP Chinese website!