Home >Backend Development >Golang >How to Retrieve a Go Function\'s Signature as a String?

How to Retrieve a Go Function\'s Signature as a String?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 10:55:15843browse

How to Retrieve a Go Function's Signature as a String?

Retrieving a Function's Signature as a String in Go

Problem:

In a Go module designed to load plugins, it's essential to ensure that a specific function with a predetermined name and signature exists within the main package. If this function is absent or does not match the expected signature, a descriptive error message is necessary. Given a function type variable, how can the underlying signature be obtained?

Solution:

Merely relying on reflect.Type.String() only provides the type's name, such as main.ModuleInitFunc. To retrieve the complete signature, we must construct it manually using the information provided by reflect.Type.

Implementation:

func signature(f interface{}) string {
    t := reflect.TypeOf(f)
    if t.Kind() != reflect.Func {
        return "<not a function>"
    }

    buf := strings.Builder{}
    buf.WriteString("func (")
    for i := 0; i < t.NumIn(); i++ {
        if i > 0 {
            buf.WriteString(", ")
        }
        buf.WriteString(t.In(i).String())
    }
    buf.WriteString(")")
    if numOut := t.NumOut(); numOut > 0 {
        if numOut > 1 {
            buf.WriteString(" (")
        } else {
            buf.WriteString(" ")
        }
        for i := 0; i < t.NumOut(); i++ {
            if i > 0 {
                buf.WriteString(", ")
            }
            buf.WriteString(t.Out(i).String())
        }
        if numOut > 1 {
            buf.WriteString(")")
        }
    }

    return buf.String()
}

Usage:

By passing a function variable to the signature() function, we can obtain the corresponding signature as a string. For example:

var myFunc ModuleInitFunc

fmt.Println(signature(func(i int) error { return nil }))
fmt.Println(signature(myFunc))
fmt.Println(signature(time.Now))
fmt.Println(signature(os.Open))
fmt.Println(signature(log.New))
fmt.Println(signature(""))

Output:

func (int) error
func (int) error
func () time.Time
func (string) (*os.File, error)
func (io.Writer, string, int) *log.Logger
<not a function>

Note:

It's crucial to recognize that it's impossible to extract the names of the parameters and result types from the signature since Go does not store or provide access to that information.

The above is the detailed content of How to Retrieve a Go Function\'s Signature as a String?. 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