You will an example here : example
And from the standard lib itself !
I think it’s a good way to aggregate a bunch of functions that need to collaborate without the need of
a shared state (I think it has something to do with fuctional style). It would be better than having an empty struct with methods on it.
// The HandlerFunc type is an adapter to allow the use of
// ordinary functions as HTTP handlers. If f is a function
// with the appropriate signature, HandlerFunc(f) is a
// Handler that calls f.
type HandlerFunc func(ResponseWriter, *Request)
// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
f(w, r)
}
It enhances polymorphism, I don’t know any language that has methods defined on functions&types It is one of my favorites features in go, it is really strange but it is beautiful.
@imatmati and @kync Thank you very much for wonderful answers with stdlib example
I have written the code which defines methods on function here(inspired by the example shared by @imatmati)
But I am still wondering, why do we need methods on a function. We can achieve the same by defining a function which expects function as a parameter like https://play.golang.org/p/nZN3b6gryFP.
If you look at Ali’s example, you’ll have an hint of the usefulness of this possibility.
It can be used to transform a function to an other type, that is to say you can build an adapter. You can find further in the source code an example of use of this technique.