Home >Backend Development >Golang >How to Select Functions from a List Based on Parameter and Return Types in Go?

How to Select Functions from a List Based on Parameter and Return Types in Go?

DDD
DDDOriginal
2024-10-29 19:29:02933browse

How to Select Functions from a List Based on Parameter and Return Types in Go?

Selecting Functions from a List in Go

In Go, it is possible to create lists of functions using slices or arrays. However, selecting functions based on specific criteria, such as return type or parameter types, requires the use of reflection.

To determine if a function takes integer arguments or returns an integer, we can use the reflect package to examine its type signature. Here is an example code that demonstrates how to achieve this:

<code class="go">package main

import (
    "fmt"
    "reflect"
)

func main() {
    funcs := make([]interface{}, 3, 3) // Use interface{} for any function type
    funcs[0] = func(a int) int { return a + 1 } // Accepts an int, returns an int
    funcs[1] = func(a string) int { return len(a) } // Accepts a string, returns an int
    funcs[2] = func(a string) string { return ":(" } // Accepts a string, returns a string

    for _, fi := range funcs {
        f := reflect.ValueOf(fi)
        functype := f.Type()
        hasIntParam := false
        hasIntReturn := false

        // Check function parameters for int type
        for i := 0; i < functype.NumIn(); i++ {
            if "int" == functype.In(i).String() {
                hasIntParam = true
                break
            }
        }

        // Check function return value for int type
        for i := 0; i < functype.NumOut(); i++ {
            if "int" == functype.Out(i).String() {
                hasIntReturn = true
                break
            }
        }

        // Print the function if it has integer parameter or return type
        if hasIntParam || hasIntReturn {
            fmt.Println(f)
        }
    }
}</code>

By using reflection, we can introspect the functions in the list and selectively print those that meet the specified criteria. The code is self-explanatory and provides a clear demonstration of how to handle this problem in Go.

The above is the detailed content of How to Select Functions from a List Based on Parameter and Return Types 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