DEV Community

Nitin Bansal
Nitin Bansal

Posted on

Methods can be passed around like normal functions... you didn't knew that.. did you?😎

#go

Methods are just like functions in that they can be used as values, and passed to other functions as parameters.

Let me show you an example:

type T struct {
  a int
}

func (t T) print(message string) {
  fmt.Println(message, t.a)
}

func (T) hello(message string) {
  fmt.Println("Hello!", message)
}

func callMethod(t T, method func(T, string)) {
  method(t, "A message")
}

func main() {
  t1 := T{10}
  t2 := T{20}
  var f func(T, string) = T.print
  callMethod(t1, f)
  callMethod(t2, f)
  callMethod(t1, T.hello)
}
>>> A message 10
>>> A message 20
>>> Hello! A message
Enter fullscreen mode Exit fullscreen mode

The part to notice is the type of such variable that holds reference to the method:

var f func(T, string) = T.print
Enter fullscreen mode Exit fullscreen mode

It has first argument of same type, and others are regular arguments needed by that method.

Top comments (0)