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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay