Pass Function as Argument to Another Function in Golang

272 阅读1分钟

in Golang, we can pass a function as argument to another function, then call it after finishing some logic, as below,

package main

import "fmt"

type Student struct {
	id   int
	name string
}

func PrintName() {
	fmt.Println("TEST")
}

func (s *Student) WithCallback(fn func()) {
	fn()
}

func main() {
	s := &Student{id: 1, name: "Tom"}
	s.WithCallback(PrintName)
}

But what if we want to pass struct's method as argument to another function, how to do that?

package main

import "fmt"

type Student struct {
	id   int
	name string
}

func (s *Student) PrintName() {
	fmt.Println(s.name)
}

func (s *Student) WithStructCallback(fn func(*Student)) {
	fn(s)
}

func main() {
	s := &Student{id: 1, name: "Tom"}
	s.WithStructCallback((*Student).PrintName)
}

(*Student).PrintName is passed to s.WithStructCallback, then in WithStructCallback, we can call it by fn(s), although PrintName does not have any arguments. Here s works as a receiver, with s.fn() working under the hood.