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

Convert func to string in golang

王林
Release: 2024-02-10 11:30:19
forward
761 people have browsed it

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
}
Copy after login

The expected result string literal is as follows:

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

This is what I tried:

testfuncstr := reflect.valueof(testfunc).string()
Copy after login

But this only gets me the following text:

"<func(int64) bool Value>",
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template