Go supports anonymous functions/closures which reminds me of Lambdas in Python, when would it be ideal to use them in your code?
I think function literals make best sense where the fact that they're closures is useful/used. Consider for example:
type handler func()
func HanldeSomething(h handler) {
//...
h()
// ...
}
func Elsewhere() {
var foo int
HandleSomething(handler(func(){
fmt.Println("debug: foo in Elsewhere is", foo)
}))
}
This way, when h
is invoked in HandleSomething
it can say/do something using the context of Elsewhere
. That's handy in many situations.
jnml already gave one of the cases where anonymous functions are useful.
I'll add that you can use them when you simply need to pass a function which won't be called elsewhere :
Goroutine launch :
go func() {
...
}()
Pass some code to a function :
http.Handle("/ws", websocket.Handler(func(ws *websocket.Conn) {
...