user7031
user7031

Reputation: 445

What purpose function types have in Go?

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!

Upvotes: 2

Views: 111

Answers (1)

Not_a_Golfer
Not_a_Golfer

Reputation: 49235

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
    })
)

Upvotes: 4

Related Questions