Implement an interface with pointger receiver

(Larry Liang) #1

When I started using interface{} in Go, I got the following error message:

X does not implement Y (x method has pointer receiver)

The solution is on stackoverflow.

I’d like to understand the reason behind it (from language design perspective).

When you define an interface, it does not specify wether the implementation uses pointer receiver or value receiver. In other words, these details are not part of the interface definition. But when you assign a concrete value to an interface typed variable, why does it care how it is implemented?


(Ivan Matmati) #2


I think it has all to do with the fact that the definition of the interface can’t assume when you’ll have to modify the state of your object (so you need a pointer) or when you’ll leave it untouched (a reference is good for that). So that an interface can’t enforce that a pointer or reference is needed for the impementation to run correctly. I’m aware it can be cumbersome to discover by “accident” that a pointer is needed in place of a reference but I guess it’s the result of the “copy by default” design of the language that makes pointers the exception .

(Boban Acimovic) #3

(Maurizio Ferreira) #4

Well, this kind of interface defintion seems to me a little restricted

It would be very useful to be able to define an interface that accept both call-by-value than call-by-reference definitions

So I request the developers to change the interface definitions.
Something like this :

type worker interface {
  getvalue () string 
* setvalue (value string)    // look at the '*' , meaning call by reference

so that having objects of this type

type myobj struct
  data string

func (o myobj) getvalue () string {

func (o * myobj) setvalue (value string) { = value

you can do something like this:

 var i worker
 i = myobj {"hello"}
 s := i.getvalue()
... do something with s...
 i.setvalue ("a different string")

This would allow you to define several kind of objects, put them on a list and call polimorfically getter and setter methods on them.

Best regards