Functions as values
Behavior is passed as an argument. That is how handlers, comparators, and strategies work without a class hierarchy.
A function type is written directly in the signature:
func Apply(n int, f func(int) int) int {
return f(n)
}
Apply(4, func(x int) int { return x * x }) returns 16. The anonymous function is created at the call site. A named function also fits, if the types match exactly. Argument names in the type do not matter. The types themselves do.
The zero value of a function type is nil. Calling a nil function panics. If the function comes from outside, decide explicitly: it is the caller's mistake, or it is empty behavior. For an optional hook, check if f != nil before the call. Do not leave it "to luck".
Function values are everywhere in the standard library: http.HandlerFunc, sort comparators, time.AfterFunc. This replaces the strategy and the template method. An interface is needed when there are several behaviors and they are tied to data. One operation is a function. Do not invent an interface with a single method only for "extensibility" if it is simpler to pass a function at the call site.
Readability
A signature func(context.Context, []byte) ([]byte, error) on a parameter is still tolerable. Two of those in a row are a reason to give the type a name: type Transform func(...). The name costs nothing at run time and helps a great deal in go doc.
Practice
A nil function
What happens when you call a variable of type
func()if nothing was stored in it?- Nothing. A call of a nil function is skipped
- A panic
- A zero value is returned without a panic
- Code with such a variable does not compile
Apply a function
Write
Apply(n int, f func(int) int) int. It must return the result of callingfonn. Assume thatfis not nil.A function or an interface
The API needs one operation, "turn a string into a string", with no extra data. What is more appropriate?
- A function type
- An interface of five methods, for growth
- Embedding a Strategy struct
- A global variable with the implementation