将func转换为Golang中的字符串字面值。

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

Convert func to string literal in golang

问题

我有一些保存在变量中的函数,并且我需要将它转换为字符串字面量:

testFunc := func(orgId int64) bool {
	return false
}

期望的结果字符串字面量如下所示:

resultStr := `func(orgId int64) bool {
	return false
}`

以下是我尝试过的方法:

testFuncStr := reflect.ValueOf(testFunc).String()

然而,这只会得到以下字面量:

"<func(int64) bool Value>"
英文:

I have some func saved in a variable and I need to convert it into a string literal:

testFunc := func(orgId int64) bool {
	return false
}

The expected result string literal is like this:

resultStr := `func(orgId int64) bool {
	return false
}`

Here is what I have tried:

testFuncStr := reflect.ValueOf(testFunc).String()

However this only get me the following literal:

&quot;&lt;func(int64) bool Value&gt;&quot;,

答案1

得分: 2

根据@BurakSerdar的说法,Go语言不是一种解释型语言,而是编译型语言,所以你可以做的事情相对有限。reflect是一个强大的包,你可以获取函数名称、函数参数的数量,甚至可以获取调用栈(用于日志记录),但你永远无法从构建的二进制文件中获取函数的源代码。

英文:

As @BurakSerdar said - Go is not a language which is interpreted, but compiled, so there's rather limited amount of stuff you can do. reflect is a powerful package - you can get function names, number of function arguments, and even call stack (which is handy for logging), but you will never be able to obtain a source code of a function from within a build binary.

huangapple
  • 本文由 发表于 2023年1月5日 02:46:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75009902.html
匿名

发表评论

匿名网友

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

确定