Consider the following example: http://play.golang.org/p/eAot_sVwND
package main
import "fmt"
type Incrementor interface {
Increment()
}
type Counter struct {
i int
Incrementor
}
func (c *Counter) Increment(){
c.i++
}
func main() {
var c Incrementor
c = &Counter{}
c.Increment()
fmt.Println(c)
}
Unfortunatelly I need to c = &Counter{}
because Counter.Increment()
implementation has a pointer receiver otherwise c.Increment()
calls won't be able to modify c.x
property:
func (c Counter) Increment(){
c.i++ // no errors, but now we increment c.x having a copy of c as context
}
How to make original implementation works without &
on c = &Counter{}
? In other words, how to avoid the need for the pointer receiver on C.Increment
implementation at all?
This is just a nit, but I think that maybe a pointer is not necessary to do that in Go.
You could consider defining an NewCounter
function that encapsulates the initialization of your type (or some 3rd party) and returns a *Counter
. Usage could look something like this:
func main() {
c := NewCounter()
c.Increment()
fmt.Println(c)
}
This is just a nit, but I think that maybe a pointer is not necessary to do that in Go.
Considering that Go uses to pass everything by value, a pointer receiver is the natural way to achieve what you want.
This is supported by the Go FAQ:
First, and most important, does the method need to modify the receiver? If it does, the receiver must be a pointer.
You would find a similar conclusion in "Things I Wish Someone Had Told Me About Golang: pointers"