Methods as objects in Go

In an earlier post, I discussed an example of using plain functions as objects. Today, I investigated solutions for using Methods as objects. As I understand it, Go methods are functions that are “bound” to a named type that is not a pointer or an interface.

	package main

	import "fmt"

	type T struct {
		S string

	func (t T) GetS1() string {
		return t.S

	func (t *T) GetS2() string {
		return t.S

	func main() {
		t := T{"hello"}
		f := (*T).GetS1
		g := (T).GetS1
		h := (*T).GetS2
		// i := (T).GetS2   // invalid method expression T.GetS2 (needs pointer receiver: (*T).GetS2)
		fmt.Printf("%v, %v %v, who is there?", f(&t) ,g(t), h(&t))

Run it yourself.

In the example, I defined a type T and the value method GetS1 and pointer method GetS2 both returning the value of field S. In the main() function, I create a T and three variables (f,g and h) to hold references to the methods GetS1 and GetS2. The statement for the variable i is commented ; this is an illegal construction. Finally, in the printing statement, I put the expressions to call the functions using the t parameter ; either using its address, or as a value.

comments powered by Disqus