The use of interface and interface function in GO language

foreword

In coding today, I saw a very classic interface usage as follows, so I checked the relevant information and found that this writing method is an interface function. This article elaborates on it.

// A Getter loads data for a key.
type Getter interface {
	Get(key string) ([]byte, error)
}

// A GetterFunc implements Getter with a function.
type GetterFunc func(key string) ([]byte, error)

// Get implements Getter interface function
func (f GetterFunc) Get(key string) ([]byte, error) {
	return f(key)
}

How to use the interface in GO language?

In the above routine, an interface is first defined, and then a function type is defined to implement the interface. So how to use the interface in the GO language?

In the GO language, an interface is a type that defines a combination of methods, but has no specific code implementation. An example of an interface definition is as follows:

type MyInterface interface {
    Method1() string
    Method2(int) int
}

In the Go language, the implementation of an interface is implicit . The implementation of an interface must be bound to a type , and the interface is implicitly implemented by implementing the method of the type. The implementation example is as follows:

type MyType struct {
    // type fields
}

func (t *MyType) Method1() string {
    return "Hello, world!"
}

func (t *MyType) Method2(n int) int {
    return n * n
}

After implementing the interface, we can pass the interface into a function as a parameter, so that different data structures that implement the interface can be passed into the function as the interface:

func MyFunction(i MyInterface) {
    fmt.Println(i.Method1())
    fmt.Println(i.Method2(8))
}

When calling this function, you can first declare the data structure that implements this interface, and then call the function:

func main() {
   t := &MyType{}
   MyFunction(t)
}

The result can be produced after calling:

Hello, world!
64

What are the benefits of using a functional type to implement an interface?

The above is that the structure used implicitly implements the interface, and the function type can also be customized to implicitly implement the interface. In this way , anonymous functions or ordinary functions (both require type conversion) can be directly passed into the function as interface parameters . The interface and implementation are as follows:

type MyInterface interface {
	Method1() string
}

type MyInterfaceFunc func()string

func (f MyInterfaceFunc) Method1()string {
	return f()
}

Define a function that takes an interface as a parameter:

func MyFunction(i MyInterfaceFunc){
   fmt.Println(i.Method1())
}

Call it using a normal function:

func Dog()string{
   return "dog dog !"
}

func main() {
   MyFunction(MyInterfaceFunc(Dog))
}

Call it using an anonymous function:

func main() {
   MyFunction(MyInterfaceFunc(func() string {
      return "hello!"
   }))
}

As you can see, the final output is correct:

dog dog !
hello!

In general, the scalability of the code is greatly increased. If there is no interface function, then if you want to implement a new function, you need to declare a new type (such as a structure), and then implement the interface implicitly. and then passed into MyFunctionthe function. With the interface function, you only need to implement the core logic, and then convert the function to the expected type and pass it in directly.

GO source code example

net/httpThe Handlerand HandlerFuncare a typical example of an interface function. The definition of Handler is as follows:

type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}
type HandlerFunc func(ResponseWriter, *Request)

func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
	f(w, r)
}

http.HandleThe classic mapping paths and handler functions can be mapped using :

func Handle(pattern string, handler Handler)

Observing this function, we can find that it is very similar to the above example, here handleris the interface type, and then HandlerFuncimplement it on the basis of , then we can use it as follows:

func home(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write([]byte("hello, index page"))
}

func main() {
	http.Handle("/home", http.HandlerFunc(home))
	_ = http.ListenAndServe("localhost:8000", nil)
}

After running, the function will be monitored localhost:8000and run home. Here it is very convenient to convert the type of home to http.HandlerFuncthen pass it in as an interface type .http.Handle

We can also use the anonymous function form:

func main() {
   http.Handle("/home", http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
      writer.WriteHeader(http.StatusOK)
      writer.Write([]byte("hello word!"))
   }))
   _ = http.ListenAndServe("localhost:8000", nil)
}

can achieve the same effect.

Guess you like

Origin blog.csdn.net/doreen211/article/details/129340313