0

In the following example, I'd like to call the setvalue() of the b object via an interface procedure.

I'd like to use an interface because I need to insert different kinds of objects in a list, possibly very big, each obeying a common interface.

However the compiler complains with the following error :

./tests.go:27:6: cannot use newbox(3) (type box) as type container in assignment: box does not implement container (setValue method has pointer receiver)

Probably I have to define the interface differently, but how?

I know I could transform the setvalue procedure in a function, returning the updated box, but since the object can be very large, and he procedure will be called several times, i'd like to pass the object via a pointer.

Really isn't there a way to define an interface method that receive the calling structure via a pointer?

package main

import "fmt"

type container interface {
  setValue (val int)
}

//--------------------------------------
// box is a kind of container

type box struct {
      value int
}

func newbox (x int) box {
    return box {x}
}

func (cnt *box) setValue(val int) {
    (*cnt).value = val
}


// -----------------------------------------------

func main() {
    var b container = newbox(3)  // HERE IS THE ERROR
    fmt.Printf("%v\n",b)
    b.setValue(5)
    fmt.Printf("%v\n",b)
}
ifnotak
  • 4,147
  • 3
  • 22
  • 36
  • 3
    Possible duplicate of [X does not implement Y (... method has a pointer receiver)](https://stackoverflow.com/questions/40823315/x-does-not-implement-y-method-has-a-pointer-receiver) – Martin Tournoij May 18 '19 at 10:03
  • 3
    tl;dr: change `newbox()` to return a pointer: `func newbox (x int) *box { return &box{x} }` (but see that link for a more complete explanation). – Martin Tournoij May 18 '19 at 10:04
  • well, this is depressing... so I can't have an interface specifying both "value" procedures (getters) than "pointer procedures" (setters) ? – Maurizio Ferreira May 18 '19 at 12:55
  • 2
    @MaurizioFerreira The [method set](https://golang.org/ref/spec#Method_sets) for a pointer type includes the methods for value receivers (`box` in the question) and pointer receivers (`*box` in the question). – Charlie Tumahai May 18 '19 at 15:40
  • Ok, so changing the function newBox to returning a pointer solves the problem. I'm able to define setters and getters procedure. Thanks to all. – Maurizio Ferreira May 18 '19 at 20:29

0 Answers0