Go methods sets — Calling method for pointer type *T with receiver T

后端 未结 1 535
逝去的感伤
逝去的感伤 2021-01-06 13:44

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

1条回答
  •  误落风尘
    2021-01-06 14:26

    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

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