Getting function arguments at runtime in Go

huangapple go评论70阅读模式
英文:

Getting function arguments at runtime in Go

问题

如何在Go中在运行时获取函数参数,我只知道如何获取函数名:

pc, file, line, ok := runtime.Caller(2)
rt := runtime.FuncForPC(pc)
return rt.Name() // Foo

我需要的是像这样的东西:

Foo(1,2,3)
// Foo_1_2_3
英文:

How to get function arguments in Go at runtime, all I know is only how to get function name:

pc, file, line, ok := runtime.Caller(2)
rt := runtime.FuncForPC(pc)
return rt.Name() // Foo

What I need is something like this:

Foo(1,2,3)
// Foo_1_2_3

答案1

得分: 4

这是一个Go语言的代码片段,它打印出了函数f1的类型以及其参数的类型。代码的输出结果是:

func(int, string)
int
string

其中,func(int, string)表示函数f1的类型是接受一个int类型和一个string类型参数的函数。接下来的两行分别表示参数a和参数b的类型是intstring

英文:

Not a full answer, but maybe this can help :

package main

import (
	"fmt"
	"reflect"
)

func main() {
	fmt.Println(reflect.TypeOf(f1))
	for index := 0; index < reflect.TypeOf(f1).NumIn(); index++ {
		fmt.Println(reflect.TypeOf(f1).In(index))
	}
}

func f1(a int, b string) {}

prints :

func(int, string)
int
string

huangapple
  • 本文由 发表于 2016年12月5日 12:30:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/40967130.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定