Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

class - Assign a new value to Golang structure field

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()
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...