Home > Article > Backend Development > How can functions and types be used to fulfill the requirements of an interface?
Function implementing interface
Question:
How do functions and types interact in an interface?
Answer:
An interface defines the required methods for a type to implement. Here's an example:
type Handler interface { ServeHTTP(*Conn, *Request) }
Example 1: Custom type implementing interface
type Counter int func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) { fmt.Fprintf(c, "counter = %d\n", ctr) ctr++ }
The Counter type implements the ServeHTTP method, satisfying the Handler interface.
Example 2: Utilizing HandlerFunc (function as a receiver)
type HandlerFunc func(*Conn, *Request) func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) { f(c, req) } var Handle404 = HandlerFunc(notFound)
Here, a HandlerFunc is a function taking a Conn and Request and returning nothing. This allows functions like notFound to be used as a handler by adding a ServeHTTP method to them through HandlerFunc. This indirect method allows for flexibility in implementing the interface.
The above is the detailed content of How can functions and types be used to fulfill the requirements of an interface?. For more information, please follow other related articles on the PHP Chinese website!