我们可以使用 Go 获取调用者的函数参数/参数值吗



我已经知道如何获取函数名称和函数位置:

func Trace(str string) string {
    pc := make([]uintptr, 10)  // at least 1 entry needed
    runtime.Callers(2, pc)
    f := runtime.FuncForPC(pc[0])
    file, line := f.FileLine(pc[0])
    str = Replace(str, "n", ` `)
    return `-- ` + fmt.Sprintf("%s:%d %s:%s", file, line, f.Name() + str)
}

但是如何获取函数参数值呢?例如,如果我在以下函数中调用该Trace函数:

func Test1(a string, b int) {
  Trace(`demo`) 
}
func main() {
  Test1(`aaaa`,123)
}

我想在函数内部获取值aaaa123 Trace而不必手动将它们从Test1传递到Trace函数

使用变量参数可能更好。怎么样?

package main
import (
  "fmt"
  "runtime"
)
func main() {
  str := trace(`demo`, 123, "me")
  fmt.Println(str)
}
func trace(str string, args ...interface{}) string {
  pc := make([]uintptr, 10) // at least 1 entry needed
  runtime.Callers(2, pc)
  f := runtime.FuncForPC(pc[0])
  file, line := f.FileLine(pc[0])
  // str = Replace(str, "n", ` `)
  return `-- ` + fmt.Sprintf("%s:%d %s:%s (%v)", file, line, f.Name(), str, args)
}

最新更新