golang function alias on method receiver

后端 未结 3 789
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 13:23

I can create method alias for an usual method:

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

var Method1 = method1

But cannot do the sam

相关标签:
3条回答
  • 2020-12-01 13:52

    This is called method expression var MethodReceiver = (*Person).methodReceiver

    Playground

    0 讨论(0)
  • 2020-12-01 14:04

    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
    
    0 讨论(0)
  • 2020-12-01 14:05

    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.

    0 讨论(0)
提交回复
热议问题