When to use functioneExpression rather than function declaration in Go?
I searched Function Expression vs Function Declaration (in JS), it's about hoisting. How about Golang?
When to use functioneExpression rather than function declaration in Go?
I searched Function Expression vs Function Declaration (in JS), it's about hoisting. How about Golang?
Anonymous functions in Go are used in various situations:
- to start a goroutine
go func() {
// body
}()
- with a defer statement
defer func() {
// body
}()
- as an argument to another function
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
// todo
})
- as a closure (examples)
Function declarations are used when you want to refer to the function by name. Maybe to call it from multiple places in your own code, or to expose it to other packages.