How Can You Adapt a Function to Implement an Interface in Go?

Linda Hamilton
Release: 2024-11-07 06:24:02
Original
289 people have browsed it

How Can You Adapt a Function to Implement an Interface in Go?

Function Implementing an Interface

In Go, an interface defines a set of methods that a type must implement. A type implements an interface if it provides all the methods declared by the interface.

Example 1: Implementing an Interface Directly

The following code defines the Handler interface and a type that implements it:

type Handler interface {
    ServeHTTP(*Conn, *Request)
}

type Counter int

func (ctr *Counter) ServeHTTP(c *http.Conn, req *http.Request) {
    fmt.Fprintf(c, "counter = %d\n", ctr)
    ctr++
}
Copy after login

Here, the Counter type has a ServeHTTP method that takes the arguments required by the Handler interface. Therefore, Counter implements the Handler interface.

Example 2: Implementing an Interface with a Function

In this example, a function called notFound is not a valid Handler type because it doesn't have the required method:

func notFound(c *Conn, req *Request) {
    // Not a valid Handler
}
Copy after login

To make notFound implement the Handler interface, it needs to be "finagled" into the following form:

// Define a type that implements ServeHTTP
type HandlerFunc func(*Conn, *Request)

func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) {
    f(c, req) // Function call with arguments
}

// Convert function to implement the interface
var Handle404 = HandlerFunc(notFound)
Copy after login

Here, HandlerFunc is a type that takes two arguments and returns nothing. By wrapping notFound within HandlerFunc and assigning it to a variable, notFound becomes a valid Handler type.

Explanation

The key concept here is that the variable Handle404 can be used as a Handler even though it's actually a function. This is because the HandlerFunc type implements the ServeHTTP method for the function. When you call Handle404.ServeHTTP, it is actually calling the notFound function.

This approach allows functions that do not implement the Handler interface directly to be used with it. It's essentially a way to "adapt" a function to fit the requirements of an interface.

The above is the detailed content of How Can You Adapt a Function to Implement an Interface in Go?. 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!