2
package main

import(
    "fmt"
)

type A func (int,int)

func (this A) Serve() {
    fmt.Println("function 1")
}

func Serve(int,int) {
    fmt.Println("function 2")
}    
func main() {
    a := A(Serve)
    a.Serve() // function 1
}

Function Serve can be converted to type A,which is also a function,but,I just don't get the idea of when and why we should use this approach,to deal with what kind of problem should we convert a function type to another?My example seems to be meaningless.

int,struct etc. are types,and what exactly is the function type different from the common known types like int and struct,from the underlying data structure perspective of view?

Thanks a lot!

1 Answer 1

4

It's a bit confusing indeed. I've seen this technique used to make an ordinary function compliant with an interface without the hassle of creating a struct and making the function a method of this struct - or other similar techniques.

A great example can be found in the standard http library. you have the type

type HandlerFunc func(ResponseWriter, *Request)

And it has the method:

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

This allows it to be used as the http.Handler interface which looks like this:

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

This allows you to call http.ListenAndServe on an ordinary function without using the default http mux. wrapping the function as an http.Handler allows you to create a "mux-less" server.

Thus you can do something like:

http.ListenAndServe(":8080",
    http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                //la di da
    })
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.