How to assign name to Anonymous function

For anonymous function (closure), go compiler will assign “func1”, “func2” as name to the function.
But is there a way to give it an explicit name?

For example, can we do as below?

var myfunc = func myfuncN(){

}

Notice the myfuncN. I find I cannot do this in Go.

It will be helpful for logging, as I want to log which function is doing the logging.

Yes, use the func keyword. Go does not support nested func declarations so you must declare the function at the package level.

To do this would defeat the purpose of the anonymous function and it seems based on Dave Cheney’s response that Go doesn’t support nested function declarations.

You could potentially solved this with runtime.FuncForPC() (Ex: https://play.golang.org/p/95a4NvnW9C), this would give you the information you want, but if you need to get more verbose you could log the whole stack with runtime/debug https://play.golang.org/p/jSKar42y0y

Log the function and the line number. You get both for free and the line no will always point you to the correct function, even if it is anonymous

1 Like

Yeah, It is sad. Nested func declaration is what I’m looking for, I know Python can do it.

Do you know where can raise request on supporting this? Or is there any plan?

This is currently what I’m doing in my logging. If the call to logging is happening in an anonymous function, I will log the file name and line number.
I’m just exploring cause I feel anonymous function is good, but it is no harm to give it name if we need to. The main benefit of anonymous function is not just being “anonymous” :smiley:

golang.org/issue/new to raise an issue.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.