Adapter function type in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Since I have just touched Golang and are not familiar with language and usage, it is strange to see this writing:

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

Why do I feel so superfluous in my heart? Define one func as a type and then implement the ServeHTTP function. Why not just use that function?

Let's take a look at http. The prototype of the Listenandserve () interface is clear:

func ListenAndServe(addr string, handler Handler) error

The second parameter of the function is one, which means that the function Handler interface needs to pass in a type that implements the ServerHTTP function.

For complex applications that may be specifically defined struct to implement an http.Handler interface, the case is passed in struct . But if a simple application does this, it's a bit out of the way, so the http package provides a HandlerFunc type to assist the user in quickly translating a function into a type that conforms to http.Handler the interface. This method is called adapter function type [1] .

The key to this technique is to define a function that conforms to the interface as a type, and then implement the function in the interface to that type, calling itself directly when implemented. When you use it, you just need to convert the custom function (the same prototype) into a type conversion.

In fact, not just the standard library to use such skills, in many golang beginners will see the groupcache use of the [2] .

Reference

[1] Https://github.com/gopherchina/conference/blob/master/2017/1.3%20Go%20coding%20in%20go%20way.pdf

[2] Https://github.com/golang/groupcache/blob/master/groupcache.go

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.