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)
}