【问题标题】:Can we get caller's function argument/parameter values using Go我们可以使用 Go 获取调用者的函数参数/参数值吗
【发布时间】:2017-10-20 11:19:37
【问题描述】:

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

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

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

【问题讨论】:

标签: go reflection


【解决方案1】:

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

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

【讨论】:

  • 嗨,我举了一个不好的例子,我的意思是,从 Trace 函数中获取调用者的参数(测试)。
猜你喜欢
  • 2021-10-27
  • 2011-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-05
  • 2017-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多