Home >Backend Development >Golang >How Can I Create a Slice of Functions with Different Signatures in Go?

How Can I Create a Slice of Functions with Different Signatures in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-26 05:01:10442browse

How Can I Create a Slice of Functions with Different Signatures in Go?

Creating a Slice of Functions with Different Signatures

Problem

How can you create a slice of functions with different signatures in Go?

Context

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.

Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn