significance of function type in Go
tags: learning go programming
content
- in Go, a
typecan have method:
type MyInt int
func (i MyInt) Double() int {
return int(i) * 2
}- but a
funccannot have method- below just doesn’t work
func hello() { ... }
func (h hello) doSomething() { ... }- BUT, if we define a function type, then a function can have method
type MyFunc func(int)int- here we define a type
- the type is a function with some specific signature
Note
basically, it’s a named type whose value is a function
- because it’s a named type, it could have method:
type MyFunc func(int)int
func (f MyFunc) DoSomething(a int) int {
return f(a)
}- irl example go’s http.HandlerFunc
type HandlerFunc func(http.ResponseWriter, *http.Request)
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
f(w, r)
}