英文:
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:
"<func(int64) bool Value>",
答案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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论