Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function implementing interface

Tags:

People also ask

Can a function implement an interface?

A class or function can implement an interface to define the implementation of the properties as defined in that interface.

What is the implementation of an interface?

To declare a class that implements an interface, you include an implements clause in the class declaration. Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class.

What are interface functions?

Interface Functions. Interface functions allow you to link your model to external data sources such as text files, databases, spreadsheets and external applications. With the exception of @FILE, interface functions are valid only in sets and data sections, and may not be used in calc and model sections.

Do all functions of an interface have to be implemented?

Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. Implement every method defined by the interface.


I want to know what is happening here.

There is the interface for a http handler:

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

This implementation I think I understand.

type Counter int

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

From my understanding it is that the type "Counter" implements the interface since it has a method that has the required signature. So far so good. Then this example is given:

func notFound(c *Conn, req *Request) {
    c.SetHeader("Content-Type", "text/plain;", "charset=utf-8");
    c.WriteHeader(StatusNotFound);
    c.WriteString("404 page not found\n");
}

// Now we define a type to implement ServeHTTP:
type HandlerFunc func(*Conn, *Request)
func (f HandlerFunc) ServeHTTP(c *Conn, req *Request) {
    f(c, req) // the receiver's a func; call it
}
// Convert function to attach method, implement the interface:
var Handle404 = HandlerFunc(notFound);

Can somebody elaborate on why or how these various functions fit together?