Go函数去神秘化[重复]

This question already has an answer here:

Just got a basic Go question regarding this code:

type Ips []string
func (a Ips) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

I believe (a Ips) is a parameter of Swap function, but why could it be not inside parenthesis?

</div>

a Ips is the receiver of the method. Its parameters are i int and j int. This is a method bound to the Ips type that two strings in the array and returns nothing.

Try it on the playground

(a Ips) is called the 'receiver'. It is the type on which the method is called. Under the covers it is in fact passed into the method like any other parameter (think back to that class where they talk about pushing arguments on the stack). In this case it is a value type, so like other values types used as parameters, a copy of the argument is made and then that's what's pushed on the stack. That also means it will go out of scope as the method returns and the stack gets popped.

The main difference is you need an instance of the receiving type in order to call the method. If the method doesn't have a receiving type, then it is packaged scoped and can be called anywhere inside the package or, if exported, can be called from the packages alias where imported.