Go功能参数

func (db *Database) VerifyEmail(emailAddress string) (*data.UserName, error) {
....
}

Can someone please help clarify 1.what and 2.why with the above function? From the docs and this book I can tell that VerifyEmail is taking in emailAdress as a parameter and returning what I think is the memory address to a username.

However, what does (db *Database) do? I mean why put that after func and before the name of the function? And what may be some reasons to pass the memory address to a function as a pointer as opposed to the variable representing it?

The (*db Database) in front of the method name is the method receiver, similar to other languages' "this", and you use a pointer if the object may be large or the method may need to change the object--if you copy it, the method can only change its copy of the object.

In Go, you can define methods using both pointer and no-pointer method receivers. The formate feels like func (t *Type) and func (t Type) respective.

So what’s the difference between pointer and non-pointer method receivers?

a) Reasons when use pointer receiver?

  1. You want to actually modify the receiver (read/write as opposed to just “read”)
  2. The struct is very large and a deep copy is expensive.
  3. Consistency: if some of the methods on the struct have pointer receivers, the rest should too. This allows predictability of behavior.
  4. If the receiver is a large struct or array, a pointer receiver is more efficient.

If you need these characteristics on your method call, use a pointer receiver.

b) Reasons when use value receiver?

  1. If the receiver is a map, func or chan, don't use a pointer to it.
  2. If the receiver is a slice and the method doesn't reslice or reallocate the slice, don't use a pointer to it.