0

I don't understand the following function definition. what's the meaning of u *Unit in this function definition? I don't think it is returned value, cannot find the answer in Go tutorial.

func (u *Unit) processImage(){

 ....
}
Flimzy
  • 68,325
  • 15
  • 126
  • 165
PZ97
  • 17
  • 1
  • 3
    It is the receiver of the method. processImage is a method defined for the type Unit. For a variable `u` of type Unit, you can call u.processImage(). processImage gets a pointer to `u`. – Burak Serdar Jul 06 '20 at 18:44
  • 9
    https://tour.golang.org/methods/4 – Inian Jul 06 '20 at 18:45
  • 1
    Please take the Tour of Go (link above) for simple questions about Go syntax. – Flimzy Jul 06 '20 at 20:38

1 Answers1

-1

In "func (u *Unit) processImage()" function, "u *Unit" is parameter/input and also receiver, it's depend what contains in processImage(). For example:

func (u *Unit) processImage() {
 u.sum = u.x + u.y
}

In this case processImage() used values of x and y fields of struct "Unit" as parameters/input to update value of "sum" and then return u (with new value of sum). A method with (u *Unit) was called Pointer receivers.

A method like below with (u Unit) was called value receivers:

func (u Unit) processImage() int {
   return u.x + u.y
}

In value receivers, u contains parameter/input values, it's not a receiver.

Farmer
  • 19
  • 2
  • I'm not sure what you expected for an answer, but if you want to know diff between Value receiver vs. pointer receiver you can refer: https://stackoverflow.com/questions/27775376/value-receiver-vs-pointer-receiver – Farmer Jul 07 '20 at 10:56
  • Thanks all for answering the question. It really helps me learning go language. – PZ97 Jul 07 '20 at 17:12