方法接收器上的 golang 函数别名 [英] golang function alias on method receiver
本文介绍了方法接收器上的 golang 函数别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以为常用方法创建方法别名:
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
在这种情况下,我在行 var MethodReciver = methodReciver
上得到了错误:
In this case I got the error on line var MethodReciver = methodReciver
:
undefined: methodReciver
完整代码:
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()
}
是否可以为 methodReceiver
创建方法别名?
Is it possible to create a method alias for methodReceiver
?
推荐答案
是的.您可以像这样创建别名:
Yes. You can make an alias like this:
var MethodReceiver = (*Person).methodReceiver
当你调用它时,你必须提供一个指向person对象的指针作为第一个参数:
When you call it, you have to provide a pointer to a person object as the first argument:
MethodReceiver(&p)
您可以在围棋操场上看到这一点.
这篇关于方法接收器上的 golang 函数别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文