Why not a mixture of value and pointer receiver?

1,878 views
Skip to first unread message

Xinhu Liu

unread,
Jan 22, 2019, 4:59:51 PM1/22/19
to golang-nuts
In "A Tour of Go" I read: 

In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.

But why not?

Methods having value receiver can be called by both value type and pointer type. The same is for methods having pointer receiver.

What is disadvantages of mixing value and pointer receiver?

Ian Lance Taylor

unread,
Jan 22, 2019, 6:01:36 PM1/22/19
to Xinhu Liu, golang-nuts
Confusion on the part of the code reader.

Ian

伊藤和也

unread,
Jan 22, 2019, 6:50:28 PM1/22/19
to golang-nuts
Yes I agree with you. It's confusing and so hard to understand.

2019年1月23日水曜日 6時59分51秒 UTC+9 Xinhu Liu:

T L

unread,
Jan 22, 2019, 7:00:42 PM1/22/19
to golang-nuts

Andrei Avram

unread,
Jan 23, 2019, 12:47:02 AM1/23/19
to golang-nuts
If it's about a method you've defined on a pointer and you want to call it on the value: https://play.golang.org/p/zMVivcaXrf3

Xinhu Liu

unread,
Jan 23, 2019, 3:43:19 AM1/23/19
to Ian Lance Taylor, golang-nuts
On the other side maybe confusion on the part of code writers if they use pointer receiver because of consistency instead of needing it?

Xinhu Liu

unread,
Jan 23, 2019, 3:52:02 AM1/23/19
to Andrei Avram, golang-nuts
Why is that a problem? I can indeed call it on value (at line 20). I got result:
hello
hello

Program exited.

I am now more confusing when I come to https://golang.org/doc/faq#different_method_sets

Am Mi., 23. Jan. 2019 um 06:47 Uhr schrieb Andrei Avram <andrei.a...@gmail.com>:
If it's about a method you've defined on a pointer and you want to call it on the value: https://play.golang.org/p/zMVivcaXrf3

--
You received this message because you are subscribed to a topic in the Google Groups "golang-nuts" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/golang-nuts/xOsuXPe1IUo/unsubscribe.
To unsubscribe from this group and all its topics, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Ivan Fraixedes

unread,
Jan 23, 2019, 6:14:51 AM1/23/19
to golang-nuts
Perhaps 

There is a handy exception, though. When the value is addressable, the language takes care of the common case of invoking a pointer method on a value by inserting the address operator automatically. In our example, the variable b is addressable, so we can call its Write method with just b.Write. The compiler will rewrite that to (&b).Write for us.

clarifies your confusion.

Xinhu Liu

unread,
Jan 23, 2019, 7:42:16 AM1/23/19
to Ivan Fraixedes, golang-nuts
Thanks Ivan. Good to know this.

So the answer to my question is just about, like Ian said, confusion for readers?


Reply all
Reply to author
Forward
0 new messages