Assign a new value to Golang structure field

前端 未结 2 834
醉话见心
醉话见心 2020-12-22 06:18

I have a problem with structure fields.

I\'ve created a class Point with one method Move() that increases or decreases object variable

相关标签:
2条回答
  • 2020-12-22 06:34

    You need to use a pointer 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()
    }
    
    0 讨论(0)
  • 2020-12-22 06:43

    That's the difference between pointer receiver and value receiver

    http://golang.org/doc/faq#methods_on_values_or_pointers

    0 讨论(0)
提交回复
热议问题