8

This is where confuses me the most while learning go. We all know that methods on T only affect the copy of T, and methods on *T will affect the actual data on T.

Why does methods on T can also be used by *T, but the opposite is not allowed? So,can you give me an example(or reason) on why they do not allow method on *T be used by T?

What is the pros and cons of this design?

1

3 Answers 3

9

There are many answers here, but non of them answer why this is the case.

First lets take the case of you having a *T and wanting to call a method which takes T. To do this, all you need to do is pass *yourT (where * is being used to dereference the pointer) to the function. This is guaranteed to be possible because you are just copying blob of memory at a known location.

Now lets say you have a T and want a *T. You may be thinking that you could just do &yourT and get its address. But life isn't always so simple. There isn't always a static address to take.


From the spec:

For an operand x of type T, the address operation &x generates a pointer of type *T to x. The operand must be addressable, that is, either a variable, pointer indirection, or slice indexing operation; or a field selector of an addressable struct operand; or an array indexing operation of an addressable array. As an exception to the addressability requirement, x may also be a (possibly parenthesized) composite literal.

You may be asking yourself why they would place these arbitrary restrictions on getting a memory address. Every variable must have some memory address, right? While this is true, optimizations can make those addresses rather ephemeral.

For example, lets say the variable was inside a map:

res := TMap["key"].pointerMethod()

In this case, you are effectively saying you want a pointer to memory being held inside a map. This would force every implementation of Go to implement map in such a way that memory addresses remain static. This would severely limit the internal structures of the runtime and give the implementers much less freedom in building an efficient map.

There are other examples such as function returns or interfaces, but you only need one example to prove that the operation is not guaranteed to be possible.


The bottom line is that computer memory isn't simple and while you may want to say "just take the address", it isn't always that simple. Taking an address that is guaranteed to be static isn't always possible. Therefore, you can't guarantee that any instance of T may be turned into a pointer and passed to a pointer method.

3

One of the best article on interface is "How to use interfaces in Go" by Jordan OREILLI.

It includes the example:

type Animal interface {
    Speak() string
}

type Dog struct {
}

func (d Dog) Speak() string {
    return "Woof!"
}

type Cat struct {
}

func (c *Cat) Speak() string {
    return "Meow!"
}

And it explains:

a pointer type can access the methods of its associated value type, but not vice versa.
That is, a *Dog value can utilize the Speak method defined on Dog, but as we saw earlier, a Cat value cannot access the Speak method defined on *Cat.

(which reflects your question)

That may sound cryptic, but it makes sense when you remember the following: everything in Go is passed by value.
Every time you call a function, the data you’re passing into it is copied. In the case of a method with a value receiver, the value is copied when calling the method.

This is slightly more obvious when you understand that a method of the following signature:

func (t T) MyMethod(s string) {
    // ...
}

is a function of type func(T, string); method receivers are passed into the function by value just like any other parameter.

Any changes to the receiver made inside of a method defined on a value type (e.g., func (d Dog) Speak() { ... }) will not be seen by the caller because the caller is scoping a completely separate Dog value.

(That is the "copy by value" part)

Since everything is passed by value, it should be obvious why a *Cat method is not usable by a Cat value; any one Cat value may have any number of *Cat pointers that point to it. If we try to call a *Cat method by using a Cat value, we never had a *Cat pointer to begin with.

Conversely, if we have a method on the Dog type, and we have a *Dog pointer, we know exactly which Dog value to use when calling this method, because the *Dog pointer points to exactly one Dog value; the Go runtime will dereference the pointer to its associated Dog value any time it is necessary.
That is, given a *Dog value d and a method Speak on the Dog type, we can just say d.Speak(); we don’t need to say something like d->Speak() as we might do in other languages.

2

You have the key to your answer in your question: methods on T only affect the copy of T. So with this information, the following excerpt from Go's FAQ should help clear the rest of the confusion:

From the Go Spec:

"The method set of any other named 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)."

If an interface value contains a pointer *T, a method call can obtain a value by dereferencing the pointer, but if an interface value contains a value T, there is no useful way for a method call to obtain a pointer.

Even in cases where the compiler could take the address of a value to pass to the method, if the method modifies the value the changes will be lost in the caller. As a common example, this code:

var buf bytes.Buffer
io.Copy(buf, os.Stdin)

would copy standard input into a copy of buf, not into buf itself. This is almost never the desired behavior.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.