golang function alias on method receiver

Basically you have 2 options:

1. Using a Method Expression

Which has the form of ReceiverType.MethodName and it yields a value of a function type:

var MethodReceiver = (*Person).methodReceiver

MethodReceiver just holds the function reference but not the receiver, so if you want to call it, you also have to pass a receiver (of type *Person) to it as its fist argument:

var p = &Person{"Alice"}
MethodReceiver(p)  // Receiver is explicit: p

2. Using a Method Value

Which has the form of x.MethodName where the expression x has a static type T:

var p = &Person{"Bob"}
var MethodReceiver2 = p.methodReceiver

A method value also stores the receiver too, so when you call it, you don’t have to pass a receiver to it:

MethodReceiver2()  // Receiver is implicit: p

Complete Example

Try it on Go Playground.

type Person struct {
    Name string
}

func (p *Person) printName() {
    fmt.Println(p.Name)
}

var PrintName1 = (*Person).printName

func main() {
    var p1 *Person = &Person{"Bob"}
    PrintName1(p1) // Have to specify receiver explicitly: p1

    p2 := &Person{"Alice"}
    var PrintName2 = p2.printName // Method value, also stores p2
    PrintName2()                  // Implicit receiver: p2
}

Output:

Bob
Alice

Leave a Comment