dtmsaqtly798322992 2013-10-17 17:08
浏览 110
已采纳

Go方法集-带有接收者T的指针类型* T的调用方法

Go spec says:

The method set of any other type T consists of all methods with receiver type T. The method set of the corresponding pointer type *T is the set of all methods with receiver *T or T (that is, it also contains the method set of T).

I understand this as: T has its own method set, while *T has it own method set plus the method set of T, because it can dereference receiver *T to T and call the method. Therefore, we can call some method with receiver *T of variable type T.

So I decided to verify my logic:

package main

import (
  "fmt"
  "reflect"
)

type User struct{}

func (self *User) SayWat() {
  fmt.Println(self)
  fmt.Println(reflect.TypeOf(self))
  fmt.Println("WAT
")
}

func main() {
  var user User = User{}

  fmt.Println(reflect.TypeOf(user), "
")

  user.SayWat()
}

http://play.golang.org/p/xMKuLzUbIf

I am a bit confused. It looks like I can call methods "of *T" on T? I have a bit wider example http://play.golang.org/p/RROPMj534A, which confuses me too. Is there some vice versa type inference?

Am I missing something, or my logic is incorrect?

Thanks!

  • 写回答

1条回答 默认 最新

  • dti3914 2013-10-17 17:34
    关注

    You cannot call a method of *T on T, but the compiler is smart enough to take the reference of the variable for you, effectively calling

    (&user).SayWat()
    

    This is explained here:

    Calls: A method call x.m() is valid if the method set of (the type of) x contains m and the argument list can be assigned to the parameter list of m. If x is addressable and &x's method set contains m, x.m() is shorthand for (&x).m().

    To understand the difference, you can for instance take a return value (non-addressable):

    func aUser() User {
        return User{}
    }
    
    ...
    
    aUser().SayWat()
    

    Fails with error:

    prog.go:40: cannot call pointer method on aUser()
    prog.go:40: cannot take the address of aUser()
    

    http://play.golang.org/p/HOTKiiOK7S

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

报告相同问题?

悬赏问题

  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'