I am come across the following question recently in using golang. Is it ok to pass a function body to a function call, like javascript.
e.g. setTimeout(function(i){console.log("input:", i)}, 1000).
It's pretty common to pass an anonymous function to another function in javascript. I was wondering if is the same in go?
package main
import (
"fmt"
)
type HandlerFunc func(int)
func main() {
// define a function as object/variable?
hnd := func(in int){
fmt.Println("func handler returns input", in);
}
a:=HandlerFunc(hnd) //pass function object/variable to type HandlerFunc
a(10)
// pass function body directly to type HandlerFunc
b:=HandlerFunc(func(_in int){
fmt.Println("another func handler returns input", _in);
})
b(100)
fmt.Println("Hello, playground")
}
They both works, but I was wondering if there is any difference between these two use, And which one is more preferable?