significance of function type in Go

tags: learning go programming

content

  • in Go, a type can have method:
type MyInt int
func (i MyInt) Double() int {
	return int(i) * 2
}
  • but a func cannot 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)
}
type HandlerFunc func(http.ResponseWriter, *http.Request)
func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	f(w, r)
}

up

down

reference