I have a problem with structure fields.
I've created a class Point with one method Move() that increases or decreases object variable x by dx. Another method Print is used to output results.
In main() a new instance is created with default x = 3 and dx = 2, then I call Move() and Print(). I expect that value of x is changed during Move() and Print() will produce Final x=5, but instead of it displays this:
2014/07/28 15:49:44 New X=5
2014/07/28 15:49:44 Final X=3
What's wrong with my code?
type Point struct {
x, dx int
}
func (s Point) Move() {
s.x += s.dx
log.Printf("New X=%d", s.x)
}
func (s Point) Print() {
log.Printf("Final X=%d", s.x)
}
func main() {
st := Point{ 3, 2 };
st.Move()
st.Print()
}
You need to use a pointer receiver here or you are only changing a copy of the original object every time. Everything is passed by value in go.
type Point struct {
x, dx int
}
func (s *Point) Move() {
s.x += s.dx
log.Printf("New X=%d", s.x)
}
func (s *Point) Print() {
log.Printf("Final X=%d", s.x)
}
func main() {
st := Point{ 3, 2 };
st.Move()
st.Print()
}
That's the difference between pointer receiver and value receiver
http://golang.org/doc/faq#methods_on_values_or_pointers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With