How can functions and types be used to fulfill the requirements of an interface?

Mary-Kate Olsen
Release: 2024-11-06 14:39:02
Original
747 people have browsed it

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)
}
Copy after login

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++
}
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!