hqinnus
(Victor Huang)
January 3, 2017, 4:43am
1
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.
dfc
(Dave Cheney)
January 3, 2017, 5:16am
2
Yes, use the func keyword. Go does not support nested func declarations so you must declare the function at the package level.
0x4445565a
(Brandon Martinez)
January 3, 2017, 9:32am
3
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
dfc
(Dave Cheney)
January 3, 2017, 1:33pm
4
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
hqinnus
(Victor Huang)
January 5, 2017, 6:05am
5
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?
hqinnus
(Victor Huang)
January 5, 2017, 6:07am
6
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”
dfc
(Dave Cheney)
January 5, 2017, 6:07am
7
system
(system)
Closed
April 5, 2017, 6:07am
8
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.