方法接收器上的golang函数别名

时间:2015-01-31 11:53:11

标签: go alias

我可以为常用方法创建方法别名:

func method1() {
    fmt.Println("method1")
}

var Method1 = method1

但是对于方法接收器不能做同样的事情:

type Person struct {
    Name string
}

func (p *Person) methodReciver() {
    fmt.Println("method reciver")
}

var MethodReciver = methodReciver

在这种情况下,我在第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()
}

Playground

是否可以为methodReceiver创建方法别名?

3 个答案:

答案 0 :(得分:23)

基本上你有两个选择:

1。使用Method Expression

其形式为ReceiverType.MethodName,它产生一个函数类型的值:

var MethodReceiver = (*Person).methodReceiver

MethodReceiver只保存函数引用,但接收器,所以如果你想调用它,你还必须传递一个接收器(类型*Person)到它作为第一个论点:

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

2。使用Method Value

其格式为x.MethodName,其中表达式x具有静态类型T

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

方法值也会存储接收器,因此当您调用它时,您不必将接收器传递给它:

MethodReceiver2()  // Receiver is implicit: p

完整示例

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
}

输出:

Bob
Alice

答案 1 :(得分:9)

是。您可以创建这样的别名:

var MethodReceiver = (*Person).methodReceiver

当你调用它时,你必须提供一个指向person对象的指针作为第一个参数:

MethodReceiver(&p)

你可以see this in action on the Go Playground

答案 2 :(得分:0)

这称为method expression var MethodReceiver = (*Person).methodReceiver

Playground