Reputation: 41
I'm writing a small project to learn some Google Go, but after few hours of coding I found that there's an issue I can't solve on my own, neither found on the internet. My project will be containing few algorithms operating on variables implementing one interface. The thing in common of all types is that I can rate them and compare by this rating so one of methods defined in Interface should be SetRating(x int) and the problem is, since Go is copying value - I can't modify any field in it. Here's example
http://play.golang.org/p/4nyxulwzNo
Trying to find out that people is using workarounds in this convention: http://play.golang.org/p/PUuOBZ4uM-
but I think this solution is a ugly, because I need to know all implementations of my interface in invoke func (to cast types) and really want to avoid this and write some universal code that can get any types implementing my Interface, just knowing that every implementation have method setRating(x int) and getRating(x int).
Any hints? (Sorry for poor English and problem's description, still learning.)
Upvotes: 4
Views: 2570
Reputation: 48330
You need to use the pointer because otherwise you are not modifying the underlying structure: http://play.golang.org/p/l3X4gTSAnF
package main
type Setter interface {
Set(x int)
Print()
}
type S1 struct {
X int
}
func (this *S1) Set(x int) {
this.X = x
println("Setting value")
}
func (this *S1) Print(){
println(this.X)
}
func main() {
var s1 Setter
s1 = &S1{}
s1.Set(5)
s1.Print()
}
Upvotes: 7