drmqzb5063 2018-02-20 11:01
浏览 16
已采纳

谁能解释这个使用方法表达式的go程序

I was going through some go tutorials but I'm not able to understand what method expressions are in go. Can anyone explain this code to me and why/when I should use it?

 // Method call with "method expression" syntax
 func main() {
    dog := Dog{}
    b := (*Dog).Bark // method expression 
    b(&dog, 5)
 }
 type Dog struct {}

 // Methods have a receiver, and can also have a pointer
 func (d *Dog) Bark(n int) {
   for i := 0; i < n; i++ {
      fmt.Println("Bark");
   }
 }
  • 写回答

1条回答 默认 最新

  • duanaoshu1989 2018-02-20 11:09
    关注

    A method expression is a function that can be called like a regular function, except that you also pass the object to act on as the first argument. This is because it needs to know which object to use.

    Normally, you would just use the following:

    d := &Dog{}
    d.Bark(5)
    

    But using a method expression, you can "save" the function, allowing you to pass it to something else. For example, you could choose to use (*Dog).Bark or (*Dog).Sit as an action, and call it from a helper. eg:

    func main() {
        var b func(*Dog, int)
        if (shouldBark) {
            b = (*Dog).Bark
        } else {
            b = (*Dog).Sit
        }
        d := Dog{}
        DoAction(b, &d, 3)
    }
    
    func DoAction(f func(*Dog, int), d *Dog, n int) {
        f(d, n)
    }
    

    The specific syntax (*Dog).Bark means that you are deriving a function for a method with pointer receiver.

    Honestly, these are not very frequently used. I would recommend you get a good grasp of the language first (eg: take the entire Go tour), then explore less used functionality at a later date.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料