Go: Functions that satisfy interfaces

I ran across this while sifting through the http package:

// 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)
}

A function that satisfies http.HandlerFunc will also automatically get a function-on-a-function (who knew) that makes it look like a struct that satisfies the http.Handler interface as well.

I had looked for a footnote about this in the section on function declarations in the Go language specification but was not successful. The receiver is little more than just a repositioned first-argument. There’s nothing that says “MUST be a struct or a func”.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s