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

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

DDD
DDDOriginal
2024-11-19 19:14:02786browse

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

How to Obtain a Function's Signature as a String in Go

Your query concerns the retrieval of the signature, a string representation of a function's type, given a function variable.

Understanding reflect.Type.String()

The reflect.Type.String() method returns the name of the type, not the full signature. When the function value is a function literal (unnamed type), it prints the signature.

Constructing the Signature Manually

To retrieve the signature of a named type, information from the reflect.Type is needed. Here's a function that constructs the signature:

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()
}

Testing the Function

Sample output of the signature function:

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(""))

Expected 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: Printing parameter and result type names is not possible due to the lack of accessible information.

The above is the detailed content of How to Get 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