Home  >  Article  >  Backend Development  >  Convert func to string in golang

Convert func to string in golang

王林
王林forward
2024-02-10 11:30:19729browse

golang 中将 func 转换为字符串

php editor Xigua will introduce to you how to convert func into a string in golang. In golang, converting func to string may encounter some challenges because the func type does not directly support conversion to string in golang. However, we can achieve this goal by using the function of reflection, as well as some other techniques. Next, we will introduce in detail how to complete this conversion process in golang so that you can better understand and apply this technology. Let’s take a look!

Question content

I have some functions saved in variables that I need to convert to string literals:

testfunc := func(orgid int64) bool {
    return false
}

The expected result string literal is as follows:

resultstr := `func(orgid int64) bool {
    return false
}`

This is what I tried:

testfuncstr := reflect.valueof(testfunc).string()

But this only gets me the following text:

"<func(int64) bool Value>",

Solution

As @BurakSerdar said - Go is not an interpreted language, but a compiled language, so what you can do is quite limited. reflect is a powerful package - you can get the function name, the number of function arguments, and even the call stack (which is handy for logging), but you will never be able to get it from Get the source code of the function in the build binary.

The above is the detailed content of Convert func to string in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete