Understand Golang's Function Type
Based on Golang’s function type spec:
1 | A function type denotes the set of all functions with the same parameter and result types |
And type identity:
1 | Two function types are identical if they have the same number of parameters and result types, corresponding parameters and result types are identical, and either both functions have variadic or neither is. Parameter and result names are not required to match |
It means that if two functions have the same signature(parameters and result types), they share one function type. Golang allows us to use the type
keyword to define a struct
(or function type
). You may think it is just a sort of coding documentation, but in practice, user-defined function types are really useful. They allow functions to implement interfaces. The most common usage is for HTTP handlers.
An HTTP handler processes and HTTP server request. Based on the interface documentation, it’s an interface with a method ServeHttp
.
1 | type Handler interface { |
Function type http.HanderFunc
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
.
1 | type HandlerFunc func(ResponseWriter, *Request) |
Which means we can define a handler below
1 | func handleGreeting(format string) http.HandlerFunc { |
This is valid return type since the anonymous function’s signature and return type is the same as http.HandlerFunc
, so we don’t need to explictly convert it. It’s the same as
1 | func handleGreeting(format string) http.HandlerFunc { |