Parameter problem of golang method

parameters of the golang method, such as the following sample code:

clipboard.png

question:
1. Is there a relationship between the parameter an of the foo () method and the an in the main () function?
2. The an in the foo () method doesn"t seem to be used. What does it mean?

Nov.05,2021

    An in
  1. main has nothing to do with an in foo. The an in foo is just the name of a local variable, and this an is called the receiver (receiver name). The an in main is only the name of a local variable, and the two variables have the same name.
  2. An in
  3. foo is the receiver name of type A, foo is a function of type A, and an is actually an instance of type A, even if it is not used in the example.

in golang, type can be compared to classes in an object-oriented language; variables of this type can be compared to objects in an object-oriented language.

An in

main is the object you instantiate; an in foo is equivalent to this (that is, the current object). You can imagine a scenario: what if you want to use Name in foo?

    An in
  1. foo is equivalent to an in main (but if type An is defined in other packages, an in main cannot access private members)
  2. you can compare this in object-oriented. If you don't need less than a, you don't have to write
  3. at all.
< hr >

if you don't understand, go ahead and ask in the comments below. I may not describe it well here, because I haven't figured out how to describe it for the time being

.

func (an A) foo () {}
this is a grammatical sugar, which translates to
func foo (an A) {

.

}

A here can be any name, usually we use this, to pass parameters using pointers.

func (this * A) foo () {}

Menu