When should we use closures?

Go noob here.I learnt about closures.I understood how to use them,however, I am pretty confused about when to use them and when not to use them.

A main benefit of a closure is that it can access variables that are defined in the parent function’s scope. (Even if the parent function goes out of scope after creating the closure.) This allows creating functions that have an internal status. Of course, you can also create a struct and a method to achieve the same, so closures are not strictly necessary for this use case. (But they usually are shorter to write than a struct and a method.)

Often, the term “closure” is used as synonym for “anonymous function” (although they are not the same). Using an anonymous function instead of a named one (with func keyword and all) is useful if the function is needed in a single place only. For example, when passing a function to filepath.Walk(), an anonymous function is often sufficient because it is not used anyhwere else.

Personal preferences and programming style may also drive the decision for or against using closures in a given situation.

If you want some particular examples and use cases, here is a great article about using closures in Go.

2 Likes

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