Home > Back-end >  Convert func to string literal in golang
Convert func to string literal in golang

Time:01-05

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>",

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related