Monday, 2 September 2013

Change state of interface value in Go (language)

Change state of interface value in Go (language)

Is it possible to change the state of a struct that implements an interface?
Here's what I mean: consider an interface IWidget with a method foo(), and
a struct Widget. Can a call to foo() update the state of the original
instance I assigned to the interface?
An example, where the state is n int:
package main
import "fmt"
type IWidget interface {
foo()
}
type Widget struct {
n int
}
func (this Widget) foo(){
this.n++
fmt.Println("foo:", this.n)
}
func main() {
myWidget := Widget{5}
var iface IWidget = &myWidget
iface.foo() // 6
iface.foo() // still 6, because the receiver is passed by value
// and the original wasn't affected by the first call
fmt.Println(myWidget) // 5, the original
myWidget.n--
fmt.Println(myWidget) // 4, of course
myWidget.n--
fmt.Println(myWidget) // 3, of course
iface.foo() // 4, i.e. 3+1: the interface is referencing the original
// because I assigned &myWidget, not myWidget
}
OK, so changes made directly on the original can be seen in the interface
value if I assign a pointer. But I still don't see how I can change the
state of the original (or even a copy) from within foo(), all the more so
because (as far as I understand) I am not allowed to declare a receiver
(this *Widget).

No comments:

Post a Comment