Clarification on code snippet

75 views
Skip to first unread message

alchemist vk

unread,
Aug 4, 2023, 12:33:12 PM8/4/23
to golang-nuts
Hi folks,
 In below code, I am invoking receiver api show() via a simple uInteger type variable instead of pointer, by which it expects to be invoked . Go being  strict with type casing and I was expecting a compiler error. But to my surprise, it compiled and executed successfully.  Can you folks please explain this behavior.

package main
import "fmt"
type uInteger int

func main() {
    var x uInteger = 10
    x.show()
}

func (x *uInteger) show() {
   fmt.Printf("In show, x = %d\n", *x)
}


Thanks in Advance,
Venkatesh

burak serdar

unread,
Aug 4, 2023, 12:39:29 PM8/4/23
to alchemist vk, golang-nuts
On Fri, Aug 4, 2023 at 10:33 AM alchemist vk <alchem...@gmail.com> wrote:
Hi folks,
 In below code, I am invoking receiver api show() via a simple uInteger type variable instead of pointer, by which it expects to be invoked . Go being  strict with type casing and I was expecting a compiler error. But to my surprise, it compiled and executed successfully.  Can you folks please explain this behavior.

package main
import "fmt"
type uInteger int

func main() {
    var x uInteger = 10
    x.show()

Above, the variable x is addressable, so the compiler passes &x to show(). 

To call a pointer receiver method of a variable, that variable has to be addressable (it doesn't have to be a pointer), so the compiler knows how to pass the address of it. Here's how it is described in the spec:

 
}

func (x *uInteger) show() {
   fmt.Printf("In show, x = %d\n", *x)
}


Thanks in Advance,
Venkatesh

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAJr0cerqTGvQA56yQWVYW3F2Ms5vbwq3YyO%2But%3DzJ%2BM4rqf81A%40mail.gmail.com.

Axel Wagner

unread,
Aug 4, 2023, 12:58:43 PM8/4/23
to burak serdar, alchemist vk, golang-nuts
Another relevant section is Calls (emphasis mine):
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():



alchemist vk

unread,
Aug 4, 2023, 8:11:16 PM8/4/23
to Axel Wagner, burak serdar, golang-nuts
Thank you Axel and burak for clarification.  Now I am able to understand the syntax. Thank you again.

With regards,
Venkatesh
Reply all
Reply to author
Forward
0 new messages