skip to content
Alvin Lucillo

Method expression in Go

/ 1 min read

💻 Tech

In Go, a method is just a function with a receiver argument. When you convert a method into function, this is called method expression. The resulting function can be called like a regular function but with a receiver argument.

type Foo struct{ Value int }

func (f *Foo) Func(value int) int { return f.Value + value }

func main() {
	fn := (*Foo).Func                      // signature for fn is func(*Foo,int) int
	fmt.Println(fn(&Foo{1}, 2))            // returns 3
	fmt.Println(((*Foo).Func)(&Foo{4}, 5)) // returns 9
}