golang function alias on method receiver
I can create method alias for an usual method:
func method1() {
fmt.Println("method1")
}
var Method1 = method1
But cannot do the same for a method receiver:
type Person struct {
Name string
}
func (p *Person) methodReciver() {
fmt.Println("method reciver")
}
var MethodReciver = methodReciver
In this case I got the error on line var MethodReciver = methodReciver
:
undefined: methodReciver
Full code:
package main
import (
"fmt"
)
type Person struct {
Name string
}
func method1() {
fmt.Println("method1")
}
var Method1 = method1
func (p *Person) methodReceiver() {
fmt.Println("method receiver")
}
var MethodReceiver = methodReceiver
func main() {
method1()
Method1()
p := Person{"Nick"}
p.methodReceiver()
p.MethodReceiver()
}
Playground
Is it possible to create a method alias for methodReceiver
?
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
Yes. You can make an alias like this:
var MethodReceiver = (*Person).methodReceiver
When you call it, you have to provide a pointer to a person object as the first argument:
MethodReceiver(&p)
You can see this in action on the Go Playground.